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.
[Java]View Plaincopyprint?
- 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 ();
- //Package The data and send it to the 9527 port on the machine
- Datagrampacket DP = new Datagrampacket (buf, Buf.length,inetaddress.getbyname ("10.100.56.210"),9527);
- //Send data
- Ds.send (DP);
- }
- //Close Resources
- 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.
[Java]View Plaincopyprint?
- 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];
- //define a packet
- Datagrampacket DP = new Datagrampacket (buf, buf.length);
- //Accept data Packets
- 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 UDP uses the socket for network chat (1)