1 package demo13; 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.SocketAddress; 8 import java.net.SocketException; 9 import java.net.UnknownHostException; 10 import java.util.Scanner; 11 12 import javax.sound.midi.MidiDevice.Info; 13 14 /** 15 * 实现客户咨询问题,客服人员回答问题 16 * @author BCh_Chen 17 * 18 */ 19 //基于UDP的Socket通信,客户端 20 public class LoginClient { 21 22 23 public static void main(String[] args) { 24 Scanner input=new Scanner(System.in); 25 System.out.println("客户端启动成功!"); 26 String info=""; 27 28 do { 29 //买礼物 30 System.out.print("请输入内容:"); 31 info=input.next(); 32 //把字符串打散成为字节数组 33 byte[] infos=info.getBytes(); 34 //对方地址和邮编(端口号) 35 InetAddress ia; 36 //快递点 37 DatagramSocket socket=null; 38 39 try { 40 ia=InetAddress.getByName("localhost"); 41 //包裹包装礼物 42 DatagramPacket dp=new DatagramPacket(infos,infos.length, ia,5000); 43 socket =new DatagramSocket(); 44 //通过快递点往外寄出礼物 45 socket.send(dp); 46 47 //接收服务器的响应 48 //准备一个空包 49 byte[] replys=new byte[1024]; 50 DatagramPacket dp1=new DatagramPacket(replys,0,replys.length); 51 //在快递点取礼物 52 socket.receive(dp1); 53 //拆礼物 54 String reply=new String(dp1.getData(),0,dp1.getLength()); 55 System.out.println("客服回复:"+reply); 56 57 } catch (UnknownHostException e) { 58 e.printStackTrace(); 59 } catch (SocketException e) { 60 e.printStackTrace(); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 }finally { 64 socket.close(); 65 } 66 67 if(info.equals("88")) { 68 break; 69 } 70 }while(true); 71 72 } 73 74 }
1 package demo13; 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.SocketAddress; 8 import java.net.SocketException; 9 import java.util.Scanner; 10 11 /** 12 * 实现客户咨询问题,客服人员回答问题 13 * @author BCh_Chen 14 * 15 */ 16 //服务器 17 public class LoginServer { 18 public static void main(String[] args) { 19 Scanner input =new Scanner(System.in); 20 System.out.println("客服端启动成功!"); 21 String reply=""; 22 do { 23 //准备一个空包 24 byte[] infos=new byte[1024]; 25 DatagramPacket dp=new DatagramPacket(infos,infos.length); 26 //快递点 27 DatagramSocket socket=null; 28 29 try { 30 31 socket=new DatagramSocket(5000); 32 //在快递点取礼物 33 socket.receive(dp); 34 //拆礼物 35 String info=new String(dp.getData(),0,dp.getLength()); 36 System.out.println("客户回复:"+info); 37 38 if(info!=null) { 39 //给客户端一个响应 40 System.out.print("请输入内容:"); 41 reply=input.next(); 42 byte[] replys=reply.getBytes(); 43 //客户端的地址 44 SocketAddress sa=dp.getSocketAddress(); 45 //打一个包裹 46 DatagramPacket dp1=new DatagramPacket(replys,0,replys.length,sa); 47 //寄出去 48 socket.send(dp1); 49 } 50 51 } catch (SocketException e) { 52 e.printStackTrace(); 53 } catch (IOException e) { 54 e.printStackTrace(); 55 }finally { 56 socket.close(); 57 } 58 59 if(reply.equals("再见")) { 60 break; 61 } 62 }while(true); 63 64 } 65 66 }
咨询问题时一般用基于UDP协议的socket编程,这时不分服务器和客户端,启动顺序没有要求。