【Java网络编程】基于 UDP 的聊天通信
使用 udp 协议,写一个基于命令行的聊天软件;客户端跟服务端分别在命令行启动之后,客户端和服务器端可以互相发送数据。
代码实现如下:
一、创建线程 sendThread 和 receiveThread
1 package com.fhcq.chat; 2 3 //双工的聊天程序 4 //可以发送数据,同时也可以等待接收数据 5 //需要使用多线程来实现 6 7 public class QICQDemo { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 12 Send send = new Send(); 13 Receive receive = new Receive(); 14 15 Thread sendThread = new Thread(send); 16 Thread receiveThread = new Thread(receive); 17 18 sendThread.start(); 19 receiveThread.start(); 20 } 21 }
二、利用线程 sendThread 实现信息的发送
1 package com.fhcq.chat; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.net.SocketException; 8 import java.net.UnknownHostException; 9 import java.util.Scanner; 10 11 public class Send implements Runnable { 12 13 @Override 14 public void run() { 15 // TODO Auto-generated method stub 16 17 try { 18 DatagramSocket datagramSocket = new DatagramSocket(); 19 InetAddress inetAddress = InetAddress.getByName("congkick"); 20 Scanner scanner = new Scanner(System.in); 21 while(true){ 22 // 阻塞 23 String nextLine = scanner.nextLine(); 24 byte[] bytes = nextLine.getBytes(); 25 DatagramPacket datagramPacket = new DatagramPacket 26 (bytes,bytes.length,inetAddress,10019); 27 datagramSocket.send(datagramPacket); 28 if (nextLine.equals("886")) { 29 break; 30 } 31 } 32 } catch (SocketException e) { 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } catch (UnknownHostException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } catch (IOException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 } 42 } 43 }
三、利用线程 receiveThread 实现信息的接收
1 package com.fhcq.chat; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.SocketException; 7 8 public class Receive implements Runnable { 9 10 @Override 11 public void run() { 12 // TODO Auto-generated method stub 13 14 // 新建datagramSocket 15 try { 16 DatagramSocket datagramSocket = new DatagramSocket(10010); 17 byte[] buf = new byte[1024]; 18 // 阻塞式方法 19 DatagramPacket datagramPacket = new DatagramPacket(buf, 1024); 20 while(true){ 21 datagramSocket.receive(datagramPacket); 22 byte[] data = datagramPacket.getData(); 23 int length = datagramPacket.getLength(); 24 String string = new String(data,0,length); 25 System.out.println(string); 26 if (string.equals("886")) { 27 break; 28 } 29 } 30 } catch (SocketException e) { 31 // TODO Auto-generated catch block 32 e.printStackTrace(); 33 } catch (IOException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } 37 } 38 }