一个简单的群聊系统,在同一个网段的群聊系统
客户端
————代码的具体实现
public class ClientRunnable implements Runnable {
private String address = "***.***.***.***";//所在同一个网段的IP
private int port = 8888;//端口号//客户端和服务器端的端口号必须一致
public ClientRunnable() {
}
public ClientRunnable(String address, int port) {
this.address = address;
this.port = port;
}
@Override
public void run() {// 要执行的程序
// 客户端传送数据用DatagramSocket
try (DatagramSocket s = new DatagramSocket();
Scanner sc = new Scanner(System.in)) {
byte[] buf = null;//定义一个发送数据的字节数组
String message = null;
DatagramPacket p = null;
while (true) {
message = sc.nextLine();
if (message.equals("886")) {
break;
}
buf = message.getBytes();
p = new DatagramPacket(buf, buf.length, InetAddress.getByName(address), port);
//发送数据
s.send(p);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务端
————代码的具体实现
public class ServerRunnable implements Runnable {
public ServerRunnable() {
}
public ServerRunnable(int port) {
this.port = port;
}
private int port = 8888;
@Override
public void run() {
try (
// 定义一个监视指定端口的DatagramSocket类
DatagramSocket s = new DatagramSocket(port);)
{
// 定义一个容器,用来存储接受的数据
byte[] bytes = new byte[1024 * 64];// udp最大的传送为64k
DatagramPacket p = new DatagramPacket(bytes, bytes.length);
while (true) {
//接受数据
s.receive(p);
System.out.println(p.getAddress().getHostAddress()+":"+new String(bytes,0,p.getLength()));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
自定义一个线程池,让他们处于同一个界面!
public class ChatRoom {
public static void main(String[] args) {
ServerRunnable s = new ServerRunnable();
ExecutersThreadPool.execute(s);
ClientRunnable c = new ClientRunnable();
ExecutersThreadPool.execute(c);
}
}
class ExecutersThreadPool {
private static ExecutorService threadPool = Executors.newCachedThreadPool();
public static void execute(Runnable task) {
if (threadPool.isShutdown()) {
threadPool = Executors.newCachedThreadPool();
execute(task);
}
threadPool.execute(task);
}
public static void shutdown() {
if (!threadPool.isShutdown()) {
threadPool.shutdown();
}
}
}
//不足:没有做一个界面!