Java使用UDP协议来实现用户通信
涉及到的知识点,UDP协议,Socket编程,多线程等。 这里实现模拟学生与老师通信,由四部分组成,一个客户端,一个服务端,两个用户分别是学生,老师。 废话不多说,直接上代码。 一,客户端
package pcq.knowledges.runnablechatsocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class ChatSendSocket implements Runnable{
private int fromPort;
private int toPort;
private String ip;
DatagramSocket socket = null;
BufferedReader reader = null;
public ChatSendSocket(int fromPort, int toPort, String ip) {
this.fromPort = fromPort;
this.toPort = toPort;
this.ip = ip;
try {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
String date = reader.readLine();
byte[] buffer = date.getBytes();
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,new InetSocketAddress(this.ip,this.toPort));
socket.send(packet);
if(date.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
二、服务端
package pcq.knowledges.runnablechatsocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ChatReceive implements Runnable{
private int port;
DatagramSocket datagramSocket = null;
BufferedReader reader = null;
private String msgFrom;
public ChatReceive(int port,String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
datagramSocket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
datagramSocket.receive(packet);
byte[] dates = packet.getData();
String receiveDate = new String(dates,0,dates.length);
System.out.println(msgFrom+":"+receiveDate);
if(receiveDate.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
datagramSocket.close();
}
}
三、学生用户
package pcq.knowledges.runnablechatsocket;
public class TalkStudent {
public static void main(String[] args) {
new Thread(new ChatSendSocket(6666,9999,"localhost")).start();
new Thread(new ChatReceive(8888,"老师")).start();
}
}
四、老师用户
package pcq.knowledges.runnablechatsocket;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new ChatSendSocket(7777,8888,"localhost")).start();
new Thread(new ChatReceive(9999,"学生")).start();
}
}
五、启动学生和老师用户,实现通信。
|