基于UDP的socket 客户端和服务端

时间:2022-11-20 22:16:40

基于UDP协议的socket 客户端和服务端


/**
* @author Mr.zhang
* 基于 UDP 协议的 socket 客户端和服务端
*/

package com.datagram.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DatagramSocketServerClient {
static DatagramSocket server = null;//全局的 socket,用于客户端发送数据包和服务端接收

/**
* 服务端,监听端口,当收到数据时,实例化一个新数据包,并返回
* @author Mr.zhang
*
*/

class Server implements Runnable {
private Integer port;
byte [] bytes = new byte[1024];
public Server (Integer port) {
this.port = port;
}

@Override
public void run() {

SimpleDateFormat sdf = null;
try {
server = new DatagramSocket(this.port);
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
while (server != null) {//监听端口
server.receive(packet);//接收数据包
String revice = new String(packet.getData(),0,packet.getLength());//将数据包转为字符串
System.out.println("服务端接收时间为:" + revice);
System.out.println("客户端主机地址为:" + packet.getAddress().getHostAddress() + " 端口为:" + packet.getPort());
sdf = new SimpleDateFormat("HH:mm:ss");
String nowTime = sdf.format(new Date());
bytes = nowTime.getBytes();
// 这里可以直接返回接收到的数据包,我这里重新实例化一个数据包返回
server.send(new DatagramPacket(bytes, bytes.length, InetAddress.getByName(packet.getAddress().getHostAddress()), packet.getPort()));
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

/**
* 客户端,发送数据包到服务端,并接收服务端返回的数据包
* @author Mr.zhang
*
*/

class Client implements Runnable {
private String host;
private Integer port;
byte [] bytes = new byte[1024];
public Client (String host , Integer port) {
this.host = host;
this.port = port;
}

@Override
public void run() {
SimpleDateFormat sdf = null;
DatagramPacket packet = null;
try {
sdf = new SimpleDateFormat("HH:mm:ss");
String nowTime = sdf.format(new Date());
bytes = nowTime.getBytes("utf-8");
packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(this.host), this.port);
server.send(packet);
server.receive(packet );
System.out.println("服务端返回:"+new String(packet.getData(),0,packet.getLength()));
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}


public static void main(String[] args) throws InterruptedException {
new Thread (new DatagramSocketServerClient().new Server(3980)).start();
Thread.sleep(1000);
new Thread (new DatagramSocketServerClient().new Client("127.0.0.1", 3980)).start();
}


}