最近计算机网络课程设计要做实验,闲来无事复习一波Java的网络编程,下面是这次用来复习的代码,由于功能简单,所以写在一个文件里面了。主要功能就是实现一个简单的UDP通信,由发送端send对象发送数据,接收端receive对象实时接受数据包并解析。
另外,要实现实时接收,应该运用多线程达到需求,将发送方建立一个线程,接收方建立一个线程。其他细节都写在注释里面,有错误的话欢迎指出~
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPChatTest {
public static void main(String[] args) throws SocketException {
/**
* 通过UDP协议完成一个聊天程序
* 一个负责发送,一个负责接受,使用多线程以达到同时执行
*/
//创建socket服务
//发送端
DatagramSocket send = new DatagramSocket(8888);
DatagramSocket receive = new DatagramSocket(10001);
new Thread(new Send(send)).start();
new Thread(new Receive(receive)).start();
}
}
//负责发送,通过UDPsocket发送
class Send implements Runnable{
//任务对象一建立,就需要socket对象】
private DatagramSocket ds;
public Send(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
//具体的发送数据的任务内容
//1.要发送的数据来自哪里?键盘录入!
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//实现键盘输入
//1.1读取数据
String line = null;
while (true) {
try {
line = bufr.readLine();
if ((line==null)) break;
//2将数据变成字节数组,封装到数据包中
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length, InetAddress.getByName(InetAddress.getLocalHost().getHostAddress()),10001);
//3.将数据包发送出去
ds.send(dp);
if ("over".equals(line)) break;
} catch (IOException e) {
e.printStackTrace();
}
}
ds.close();
}
}
//负责接收
class Receive implements Runnable{
private DatagramSocket ds;
public Receive(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
while (true) {
//接受任务
//1.接收到的数据要存到数据包中,而数据包中必须有字节数组
byte[] bytes = new byte[1024];
//2.创建数据包对象
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
//3.将数据存入数据包
try {
ds.receive(dp);
} catch (IOException e) {
e.printStackTrace();
}
//4.获取数据
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println("ip:" + ip + "\n" + "port:" + port + "\n" + "message:" + str);
if ("over".equals(str)){
System.out.println(ip+"......离开");
}
}
}
}