import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* 用多线程来实现聊天
*
* 写两个类,一个是发送(sendSocket),一个是接收(receiveSocket)
* 两个类都集成Runnable,然后都在run方法中重写实现的方法
* 然后两个线程交替执行,实现了同时进行聊天和接收信息功能
* @author user
*
*/
public class Demo {
public static void main(String[] args) throws SocketException {
DatagramSocket dendSocket = new DatagramSocket(8888);
DatagramSocket receiveSocket = new DatagramSocket(10000);
sendSocket send = new sendSocket(dendSocket);
receviceSocket receive = new receviceSocket(receiveSocket);
Thread t1 = new Thread(send);
Thread t2 = new Thread(receive);
t1.start();
t2.start();
}
}
/**
* 发送端程序
* @author user
*
*/
class sendSocket implements Runnable{
private DatagramSocket ds;
public sendSocket(DatagramSocket ds){
this.ds = ds;
}
@Override
public void run() {
try {
while(true){
BufferedReader bis = new BufferedReader(new InputStreamReader(System.in,"utf-8"));
String line = bis.readLine();
// System.out.println("ddd:"+bis.);
byte[] buf = line.getBytes("utf-8");
DatagramPacket dp = new DatagramPacket(buf,0,buf.length,InetAddress.getByAddress(new byte[]{127,0,0,1}),10000);
ds.send(dp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ds.close();
}
}
}
/**
* 接收端程序
* @author user
*
*/
class receviceSocket implements Runnable{
private DatagramSocket ds;
public receviceSocket(DatagramSocket ds){
this.ds = ds;
}
@Override
public void run() {
try{
while(true){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength(),"utf-8");
System.out.println(str);
}
}catch(Exception e){
e.printStackTrace();
}finally{
ds.close();
}
}
}
|
|