计网实验一。
时间:2020-12
实验目的
假设Tom和Jerry利用Java UDP进行聊天,请为他们编写程序。具体如下:
(1)Tom和Jerry聊天的双方都应该具有发送端和接收端;
(2)利用DatagramSocket与DatagramPacket;
(3)实现 java.lang.Runnable类,重写 run()方法。
部分源码
jerry端启动类
public class UDPSocket_Jerry {
public static void main(String[] args) {
// 分别启动发信息线程和收消息线程
Thread thread1 = new Thread(new UDPSocketClientthread());
Thread thread2 = new Thread(new UDPSocketServerthread());
thread1.start();
thread2.start();
}
}
tom端的server类
package tom;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UDPSocketServerthread implements Runnable {
byte[] ibuf = new byte[1024];
String message;
Scanner scanner = new Scanner(System.in);
DatagramPacket datagramPacket;
{
try {
datagramPacket = new DatagramPacket(ibuf, ibuf.length, InetAddress.getByName("127.0.0.1"), 8081);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
DatagramSocket ds;
{
try {
ds = new DatagramSocket(8083, InetAddress.getByName("127.0.0.1"));
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
message = scanner.nextLine();
datagramPacket.setData(message.getBytes());
try {
assert ds != null;
ds.send(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
效果
(绿色为该端发送的消息,黑色为对面发送的
jerry端
tom端
链接
git:Socket2012
jdk:1.7.0_80