设计要求:单线程模式,客户端只发送数据,数据的来源为键盘录入,服务器端只接收数据,当客户端发送886的时候,客户端和服务器端都退出。
1. 发送端:
public class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds)
{ this.ds= ds; } @Override break; } ds.close(); } catch (Exception e) { } }}
2. 接收端:
public class Reci implements Runnable {
private DatagramSocket ds;
public Reci(DatagramSocket ds) { this.ds= ds; }
@Override public void run() { // TODO Auto-generated method stub try { while(true){
byte[] buf=new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ipString=dp.getAddress().getHostAddress(); int port =dp.getPort(); String data= new String(dp.getData(),0,dp.getLength());
System.out.println("ip :"+ipString+"port :"+port+"data :"+data);
if(data.equals("886")) { System.out.println(ipString+"...退出聊天室"); } } } catch (IOException e) {
} }
}
3. 单线程进程启动
public class ChatMultiThreadDemo {
public static void main(String[] args) throws SocketException {
DatagramSocket send = new DatagramSocket(); DatagramSocket reci = new DatagramSocket(10001);
new Thread(new Send(send)).start(); new Thread(new Reci(reci)).start();
} }
|
请发表评论