本篇文章给大家谈谈用java语言编写对话,以及用java编写聊天程序对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
1、求用java语言做一个简单的聊天程序2、,用Java语言编写一个程序,用两个线程模拟对话,任何一个线程都可以随时收发信息.3、用JAVA 编写简单网络聊天程序4、用java编写一个程序,程序运行时弹出一个输入对话框,用户使用该对话5、在java中怎么定义一个男和女进行对话
求用java语言做一个简单的聊天程序
嗯,我这里有!你要求这样,代码很长的!邮箱也不留?怎么给你?
已经发送到你们的邮箱咯!请查收!~但愿能帮到你们!~
,用Java语言编写一个程序,用两个线程模拟对话,任何一个线程都可以随时收发信息.
//server
public class TestNIOSocketServer{
// 通道管理器
private Selector selector;
public void initServer(int port) throws Exception{
// 获得一个ServerSocket通道
ServerSocketChannel serverChannel=ServerSocketChannel.open();
// 设置通道为 非阻塞
serverChannel.configureBlocking(false);
// 将该通道对于的serverSocket绑定到port端口
serverChannel.socket().bind(new InetSocketAddress(port));
// 获得一耳光通道管理器
this.selector=Selector.open();
// 将通道管理器和该通道绑定,并为该通道注册selectionKey.OP_ACCEPT事件
// 注册该事件后,当事件到达的时候,selector.select()会返回,
// 如果事件没有到达selector.select()会一直阻塞
serverChannel.register(selector,SelectionKey.OP_ACCEPT);
}
// 采用轮训的方式监听selector上是否有需要处理的事件,如果有,进行处理
public void listen() throws Exception{
System.out.println(“start server”);
// 轮询访问selector
while(true){
// 当注册事件到达时,方法返回,否则该方法会一直阻塞
selector.select();
// 获得selector中选中的相的迭代器,选中的相为注册的事件
Iterator ite=this.selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey key=(SelectionKey)ite.next();
// 删除已选的key 以防重负处理
ite.remove();
// 客户端请求连接事件
if(key.isAcceptable()){
ServerSocketChannel server=(ServerSocketChannel)key.channel();
// 获得和客户端连接的通道
SocketChannel channel=server.accept();
// 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以发送消息给客户端
channel.write(ByteBuffer.wrap(new String(“hello client”).getBytes()));
// 在客户端 连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限
channel.register(this.selector,SelectionKey.OP_READ);
// 获得了可读的事件
//sentCommond(channel,”你好,世界”);
}else if(key.isReadable()){
read(key);
}
Thread.sleep(1000);
}
}
}
public void sentCommond(SocketChannel channel,String commond) throws IOException{
Charset charset = Charset.forName(“UTF-8”);
channel.write(charset.encode(commond).asReadOnlyBuffer());
channel.register(this.selector,SelectionKey.OP_READ);
}
// 处理 读取客户端发来的信息事件
private void read(SelectionKey key) throws Exception{
// 服务器可读消息,得到事件发生的socket通道
SocketChannel channel=(SocketChannel)key.channel();
// 穿件读取的缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
channel.read(buffer);
byte[] data=buffer.array();
String msg=new String(data).trim();
System.out.println(“server receive from client: “+msg);
ByteBuffer outBuffer=ByteBuffer.wrap(“hello client”.getBytes());
channel.write(outBuffer);
}
public static void main(String[] args) throws Throwable{
TestNIOSocketServer server=new TestNIOSocketServer();
server.initServer(8989);
server.listen();
}
}
//client
public class TestNIOSocketClient{
// 通道管理器
private Selector selector;
/**
* * // 获得一个Socket通道,并对该通道做一些初始化的工作 * @param ip 连接的服务器的ip // * @param port 连接的服务器的端口号 * @throws IOException
*/
public void initClient(String ip,int port) throws IOException{ // 获得一个Socket通道
SocketChannel channel=SocketChannel.open(); // 设置通道为非阻塞
channel.configureBlocking(false); // 获得一个通道管理器
this.selector=Selector.open(); // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调
// 用channel.finishConnect();才能完成连接
channel.connect(new InetSocketAddress(ip,port));
// 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。
channel.register(selector,SelectionKey.OP_CONNECT);
}
/**
* * // 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 * @throws // IOException
*
* @throws Exception
*/
@SuppressWarnings(“unchecked”)
public void listen() throws Exception{ // 轮询访问selector
while(true){
// 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
// 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
// selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
selector.select(); // 获得selector中选中的项的迭代器
Iterator ite=this.selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey key=(SelectionKey)ite.next(); // 删除已选的key,以防重复处理
ite.remove(); // 连接事件发生
if(key.isConnectable()){
SocketChannel channel=(SocketChannel)key.channel(); // 如果正在连接,则完成连接
if(channel.isConnectionPending()){
channel.finishConnect();
} // 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以给服务端发送信息哦
channel.write(ByteBuffer.wrap(new String(“hello server!”).getBytes()));
// 在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
channel.register(this.selector,SelectionKey.OP_READ); // 获得了可读的事件
}else if(key.isReadable()){
read(key);
}
}
}
}
private void read(SelectionKey key) throws Exception{
SocketChannel channel=(SocketChannel)key.channel();
// 穿件读取的缓冲区
ByteBuffer buffer=ByteBuffer.allocate(1024);
channel.read(buffer);
byte[] data=buffer.array();
String msg=new String(data).trim();
System.out.println(“client receive msg from server:”+msg);
ByteBuffer outBuffer=ByteBuffer.wrap(“hello server”.getBytes());
channel.write(outBuffer);
}
/**
* * // 启动客户端测试 * @throws IOException
*
* @throws Exception
*/
public static void main(String[] args) throws Exception{
TestNIOSocketClient client=new TestNIOSocketClient();
client.initClient(“www.easyaq.com”,8989);
client.listen();
}
}
用JAVA 编写简单网络聊天程序
/**
* 基于UDP协议的聊天程序
*
* 2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = “172.18.8.255”;
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel(“IP地址:”);
JLabel lblMSG = new JLabel(“消息:”);
JButton btnSend = new JButton(“发送”);
byte [] buf;
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add(“【消息来自】◆” + dp.getAddress().getHostAddress() + “◆”+”【说】:” + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println(“test”);
int n=JOptionPane.showConfirmDialog(null,”是否要退出?”,”退出”,JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle(“〓聊天室〓”);
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,”发送消息不能为空”,”提示”,JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText(“”);//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText(“”);//清空消息框
txtMSG.requestFocus();
}
}
}
用java编写一个程序,程序运行时弹出一个输入对话框,用户使用该对话
package cn.fu;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Window.Type;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setTitle(“工具”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setToolTipText(“”);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(121, 86, 194, 21);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel(“请输入10位数以内的字符串”);
lblNewLabel.setBounds(145, 59, 194, 15);
contentPane.add(lblNewLabel);
JButton btnNewButton = new JButton(“确定”);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ca = textField.getText();
int n = ca.length();
if (n 10) {
JOptionPane.showMessageDialog(null, “对不起,您输入的字符串长度超过10”,
“错误提示”, JOptionPane.ERROR_MESSAGE);
} else if (n = 0 || n = 10) {
JOptionPane.showMessageDialog(null, “字符串长度为” + n, “提示”,
JOptionPane.PLAIN_MESSAGE);
}
}
});
btnNewButton.setBounds(172, 130, 93, 23);
contentPane.add(btnNewButton);
}
}
在java中怎么定义一个男和女进行对话
在面向对象语言中,万物都可以用对象来表示,你所说的男女亦是如此。
定义1个类:人类; ——-人类应有的属性:姓名、年龄、性别以及所说的话(根据题意)
再定义两个类:男人、女人,这两个类都继承人类; —— 男人类中定义性别为男,女人类中定义性别为女,以区分这两个类的不同。
以上,就将男性和女性抽象出来了。
下一步,再定义一个测试类,在main方法中new 出男性 和 女性类的实例,就可以进行对话了。
用java语言编写对话的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于用java编写聊天程序、用java语言编写对话的信息别忘了在本站进行查找喔。