java 網絡編程(四)----UDP進階篇聊天小程序

設計要求:單線程模式,客戶端只發送數據,數據的來源爲鍵盤錄入,服務器端只接收數據,當客戶端發送886的時候,客戶端和服務器端都退出。服務器

1. 發送端:ide

public class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds)this

{
      this.ds= ds;
}
@Override

try {

BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String lines = null;

while((lines=bufr.readLine())!=null)
{

byte[] buf=lines.getBytes();
DatagramPacket dp= new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.5.255"),10001);
ds.send(dp);

if("886".equals(lines))
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) {

}
}
ip

}ci

3. 單線程進程啓動get

public class ChatMultiThreadDemo {io

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(); }}

相關文章
相關標籤/搜索