Author: Ching
Original address: http://blog.csdn.net/qingdujun/article/details/39312065
This article demonstrates that using a socket for a network chat, the implementation of the client to the server side has been sending messages, when sending "886", indicating that the client shutdown.
1) client, send data to the server, send "886" to shut down the client.
2) The server, has been listening to 9527 ports, the monitoring of the data printed on the console.
First, the client: the main use of the input from the keyboard, and when the "886" packet is sent, close the client.
Package Udp.send2.qdj;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;public class CUdpSend2 {public static void Main (string[] args) throws Exception {//Send data from native 1234 port datagramsocket ds = new Datagramsocket (1234);// Input from keyboard BufferedReader BUFR = new BufferedReader (new InputStreamReader (system.in)); String line = Null;while ((Line=bufr.readline ())!=null) {if ("886". Equals (line)) break;byte[] buf = Line.getbytes ();// The data is packaged and sent to the 9527 port of the Datagrampacket DP = new Datagrampacket (buf, Buf.length,inetaddress.getbyname ("10.100.56.210"), 9527);//Send data Ds.send (DP);} Close resource Ds.close ();}}
Client Display effect:
Second, the server side, the main is always listening to 9527 ports, and the monitoring of the data to print to the console.
1) The console can be dragged and released, if need to put in the "minimize" to the left of the bottom of the option is OK.
2) Switch the console, you can click on the "minimize" to the left of the 2nd option.
Package Udp.rece2.qdj;import Java.net.datagrampacket;import Java.net.datagramsocket;public class CUdpRece2 {public static void Main (string[] args) throws exception{//monitor 9527 port datagramsocket ds = new Datagramsocket (9527); while (true) { byte[] buf = new byte[1024];//defines a packet datagrampacket DP = new Datagrampacket (buf, buf.length);//Accept Packet Ds.receive (DP);// Extract data String IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0,dp.getlength ()); SYSTEM.OUT.PRINTLN ("IP number:" +ip+ "\ n data:" +data);}}}
server side, display effect:
References: Java video Bi Xiangdong presenter
Original address: http://blog.csdn.net/qingdujun/article/details/39312065
Java uses the socket for Web chat (1)