通过Socket和UDP实现多线程的聊天程序
今天写了一个多线程的聊天程序,是通过Socket和UDP实现的
package learning;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*
* 聊天程序,多线程,多人同时聊天。。。by 杜少
*/
public class Talk {
public static void main(String[] args) throws Exception{
DatagramSocket sendsocket=new DatagramSocket();
DatagramSocket getsocket=new DatagramSocket(10002);
new Thread(new send(sendsocket)).start();
new Thread(new get(getsocket)).start();
}
}
class send implements Runnable{
private DatagramSocket ds;
public send(DatagramSocket ds){
this.ds=ds;
}
public void run(){
try{
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=bufr.readLine())!=null){
if("666".equals(line))
break;
byte[] buf=line.getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("10.15.2.253"),10002);
ds.send(dp);
}
}catch(Exception e){
throw new RuntimeException("发送端失败");
}
}
}
class get implements Runnable{
private DatagramSocket ds;
public get(DatagramSocket ds){
this.ds=ds;
}
public void run(){
try{
while(true){
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+":"+data);
}
}catch(Exception e){
throw new RuntimeException("接收端失败");
}
}
}