网络编程就是用来实现互连的不同计算机上运行的程序进行数据交换。
使用UDP协议搭建聊天室:
一、首先创建一个线程池
public class ThreadPoolUtil {
private static ExecutorService threadPool = Executors.newCachedThreadPool();
public static void execute(Runnable command){
if(threadPool.isShutdown()){
threadPool = Executors.newCachedThreadPool();
execute(command);
}else{
threadPool.execute(command);
}
}
public static void shutdown(){
if(!threadPool.isShutdown()){
threadPool.shutdownNow();
}
}
}
二、建立一个客户端:
public class ClientRunnable implements Runnable {
private String ip = "localhost";
private int port = 8888;
public ClientRunnable() {
}
public ClientRunnable(String ip, int port) {
this.ip = ip;
this.port = port;
}
@Override
public void run() {
//1.创建客户端DatagramSocket对象
try (DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);){
//2.创建数据包,在包中指定ip地址,端口号,内容
String content = null;
byte [] buf = null;
while(true){
content = sc.nextLine();
if(content.equals("886")){
break;
}
buf = content.getBytes();
socket.send(new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、建立一个服务端:
public class ServerRunnable implements Runnable {
private int port = 8888;
public ServerRunnable(){
}
public ServerRunnable(int port) {
this.port = port;
}
@Override
public void run() {
//1.创建DatagramSocket对象,并监听指定端口号
try (DatagramSocket socket = new DatagramSocket(port);){
//2.创建存储数据的字节数组容器
byte [] buf = new byte [1024*64];
DatagramPacket p = new DatagramPacket(buf, buf.length);
//3.循环接收数据
while(true){
socket.receive(p);
System.out.println("ip= " + p.getAddress().getHostAddress() + "content= " + new String(p.getData(),0,p.getLength()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、使用线程池运行服务端和客户端
public class ChatRoom {
public static void main(String[] args) {
ServerRunnable serverRunnable = new ServerRunnable(8888);
ThreadPoolUtil.execute(serverRunnable);
ClientRunnable clientRunnable = new ClientRunnable("192.168.1.255",8888);
ThreadPoolUtil.execute(clientRunnable);
}
}