JAVA通过多线程实现双方实时聊天
二、使用步骤
1.定义实现Runnable接口的收发消息的javabean类
1.发送消息
代码如下:发送bean类
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class MySendChat implements Runnable{ private int port; private String address; public MySendChat(){ } public MySendChat(int port, String address) { this.port = port; this.address = address; } public boolean send() throws IOException { DatagramSocket ds = new DatagramSocket(); //打包数据 Scanner sc = new Scanner(System.in); String str = sc.nextLine(); byte[] bytes = str.getBytes(); InetAddress address1 = InetAddress.getByName(address); DatagramPacket dp = new DatagramPacket(bytes ,bytes.length ,address1 ,port); ds.send(dp); ds.close(); if(str.equals("bye")) return false; return true; } @Override public void run() { while (true){ try { if (!send()) break; } catch (IOException e) { throw new RuntimeException(e); } } } }
2.接收消息
代码如下:接收bean类
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class MyReceiveChat implements Runnable{ private int port; public MyReceiveChat() { } public MyReceiveChat(int port) { this.port = port; } public boolean receive() throws IOException { DatagramSocket ds = new DatagramSocket(port); byte[] bytes = new byte[1024]; DatagramPacket dp = new DatagramPacket(bytes , bytes.length); ds.receive(dp); //解析数据 byte [] data = dp.getData(); int length = dp.getLength(); InetAddress address = dp.getAddress(); int getport = dp.getPort(); System.out.println(address + " "+ getport+ ":" + new String(data , 0, length)); ds.close(); if(new String(data , 0 ,length).equals("bye")) return false; return true; } @Override public void run() { while (true){ try { if (!receive()) break; } catch (IOException e) { throw new RuntimeException(e); } } }
2.Main函数及其实现效果
代码如下(示例):
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
MySendChat S = new MySendChat(10087 ,"127.0.0.1");
MyReceiveChat R = new MyReceiveChat(10086);
Thread t1 = new Thread(S);
Thread t2 = new Thread(R);
t1.start();
t2.start();
}
}
效果