前几天写了个小程序,,模拟一个聊天室,,但是只开了两个线程。
/**
* 多线程聊天室
*/
public class ChatRoom {
public static void main(String[] args) {
SendThread send = new SendThread(null,1125);
ReceiveThread receive = new ReceiveThread(1125);
Thread t1 = new Thread(send);
Thread t2 = new Thread(receive);
t1.start();
t2.start();
}
}
--------------------------------------------------------------------------------------------
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* 接受数据
*/
public class ReceiveThread implements Runnable {
private int port;
public ReceiveThread(int port) {
this.port = port;
}
@Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(port);
while (true) {
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
ds.receive(dp);
String hostName = dp.getAddress().getHostName();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("from: " + hostName + "\t" + "data: " + s);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
-----------------------------------------------------------------------------------------------------
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;
import java.net.UnknownHostException;
/**
* 发送数据线程
*
*/
public class SendThread implements Runnable {
/**
* 接收端的主机ip号
*/
private String ip;
/**
* 端口号
*/
private int port;
public SendThread(String ip, int port) {
this.ip = ip;
this.port = port;
}
@Override
public void run() {
DatagramSocket ds = null;
DatagramPacket dp = null;
// IP地址对象
InetAddress address = null;
try {
// 初始化IP地址对象
if (ip == null) {
address = InetAddress.getLocalHost();
} else {
address = InetAddress.getByName(ip);
}
ds = new DatagramSocket();
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("请输入聊天内容:");
while (true) {
String line;
line = br.readLine();
if (line.equals("over")) {
System.out.println("聊天结束。");
break;
}
// DatagramPacket(byte[] buf, int length, InetAddress address,
// int port)
dp = new DatagramPacket(line.getBytes(), line.getBytes().length,
address, port);
ds.send(dp);
}
br.close();
} catch (SocketException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ds.close();
}
}
}
|