而UDP协议就不同了,它不需要服务端,发出去的文件也不需要确定与对方是否连接成功!(就像发短信,时时刻刻都可以发,无论对方状态如何)。
简介
聊天室最重要的是能够相互发送消息,接收消息,这里就涉及到了多线程技术。
本例适合Java初学者练习参考使用,建议收藏,动手编写代码,体会每一行的作用。
源码
发送聊天信息类
package UDPchatEachOther;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class TalkSend implements Runnable {
DatagramSocket socket =null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) throws Exception {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
//创建连接 并读取控制台数据
socket=new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
}catch (Exception e){
e.printStackTrace();
}
}
接收聊天信息类
package UDPchatEachOther;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TalkReceive implements Runnable {
DatagramSocket socket =null; //建立连接
private int port; //端口号
private String msgFrom; //发送方的名字
public TalkReceive(int port,String msgFrom) {
this.port = port;
this.msgFrom=msgFrom;
try{
socket = new DatagramSocket(port);
}catch (Exception e){
e.printStackTrace();
}
}
用户一
package UDPchatEachOther;
public class user1 {
public static void main(String[] args) throws Exception {
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"user2")).start();
}
}
用户二
package UDPchatEachOther;
public class user2 {
public static void main(String[] args) throws Exception {
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"user1")).start();
}
}