package com.lzj.test8_4;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpServerThread extends Thread{
private static int count = 0;
private DatagramSocket socket;
public UdpServerThread(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
while(true){
try {
//接收来自客户端传来的消息
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
socket.receive(packet);
System.out.println(new String(bytes));
//向客户端发送消息
InetAddress addr = packet.getAddress();
int port = packet.getPort();
StringBuilder sb = new StringBuilder();
sb.append("服务器返回:");
sb.append(count++);
sb.append(new String(bytes));
sb.append("呵呵");
byte[] res = sb.toString().getBytes();
DatagramPacket cpacket = new DatagramPacket(res,res.length,addr,port);
socket.send(cpacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}