import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ChatRoomByDemo {
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 10086;
SendThread st = new SendThread(host, port);
ReceiveThread rt = new ReceiveThread(port);
Thread t1 = new Thread(st);
Thread t2 = new Thread(rt);
t1.start();
t2.start();
}
}
class ReceiveThread implements Runnable {
private int port;
private DatagramSocket dsSocket;
private String endStr = "886";
/**
* @param endStr the endStr to set
*/
public void setEndStr(String endStr) {
this.endStr = endStr;
}
public ReceiveThread(int port) {
this.port = port;
}
@Override
public void run() {
try {
dsSocket = new DatagramSocket(port);
while (true) {
byte[] bys = new byte[1024];
DatagramPacket dPacket = new DatagramPacket(bys, bys.length);
dsSocket.receive(dPacket);
String ip = dPacket.getAddress().getHostAddress();
String msg = new String(dPacket.getData(), 0, dPacket.getLength());
System.out.println("receive("+ip + "):" + msg);
if (msg.equals(endStr)) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dsSocket != null) {
dsSocket.close();
System.out.println("socket close");
}
}
}
}
class SendThread implements Runnable {
private String host;
private int port;
private DatagramSocket dsSocket;
private String endStr = "886";
/**
* @param endStr the endStr to set
*/
public void setEndStr(String endStr) {
this.endStr = endStr;
}
public SendThread(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void run() {
try {
dsSocket = new DatagramSocket();
System.out.print("输入聊天内容:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
InetAddress address = InetAddress.getByName(host);
while ((msg = br.readLine()) != null) {
byte[] bys = msg.getBytes();
DatagramPacket dp = new DatagramPacket(bys, bys.length, address, port);
dsSocket.send(dp);
System.out.println("send:"+msg);
if (endStr.equals(msg)) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dsSocket != null) {
dsSocket.close();
}
}
}
}
网友评论