Works exhibition, our works "Super Fly Chat" The main function is to chat, including LAN chat, outdoor chat, and so on, although it was implemented with VB (Winsock Control), but the idea of each programming is similar, so learn Java socket programming, feel kind ah.
Concept Understanding
A socket is also called a socket, which is used to make a request to a host in the network or to answer a request made in the network.
The article begins with a brief look at the two protocols: TCP and UDP.
TCP
TCP (Transmission Control Protocol Protocol) is a connection-oriented, reliable, byte-stream-based communication protocol located at the transport layer. Of these three features, the connection is like a phone call, the two sides of the phone must remain connected to call; reliable as the video on QQ, one side to send video requests, the other party must agree to establish a video connection, can also say that the security is good; based on the byte stream, continue to see the following line.
The most important idea of TCP is the famous "three-time handshake":
The client sends the request message to the server, and the client replies to the client after receiving the service, and the clients acknowledge receiving the reply from the server. After three handshake finishes, the client establishes a reliable link to the server.
UDP
UDP (User Datagram Protocol Subscriber Datagram Protocol) provides simple but unreliable information delivery services. Very much like the life of the letter or e-mail, do not need to ask the other party's consent, do not need to establish a connection with the other, you can send the data out, but there is no guarantee that the data sent out to ensure that the destination without error.
Remember to use Winsock in VB, first drag two Winsock controls on the form (the equivalent of instantiation), and then set the IP, port, transport protocol, you can communicate. Only in Java, TCP protocol-based communication needs to be done with serversocket and sockets, and UDP protocol-based communication needs to be done with Datagramsocket.
The following is a description of how the network communicates in Java from two aspects of TCP and UDP.
TCP protocol-based communication
Service-side code:
Import Java.io.*;import java.net.*;p ublic class Server {public static void main (string[] args) {InputStream is=null; OutputStream os=null;try{serversocket ss=new ServerSocket (5566); Create a server socket and bind to the 5566 port socket s=ss.accept (); Is=s.getinputstream (); Os=s.getoutputstream ();D Atainputstream dis=new DataInputStream (IS);D ataoutputstream dos=new dataoutputstream (OS); String message=null;if ((Message=dis.readutf ())!=null) { //receives and outputs the information sent by the client of this connection System.out.println ("Client:" + message);} Dos.writeutf ("Hello, client! "); Send information to this connected client Dis.close ();d os.close (); S.close ();} catch (Connectexception ex) {ex.printstacktrace ();} catch (IOException ex) {ex.printstacktrace ();}}}
Client code:
Import Java.io.*;import java.net.*;p ublic class Client {public static void main (string[] args) {InputStream IS=NULL;OUTPU TStream os=null;try{socket s=new Socket ("127.0.0.1", 5566); Create a socket and connect it to 127.0.0.1 address (native) of 5566 Port Is=s.getinputstream (); Os=s.getoutputstream ();D Atainputstream dis=new DataInputStream (IS);D ataoutputstream dos=new dataoutputstream (OS);d Os.writeutf ("Hello, server! "); Send information to the server string Message=null;if ((Message=dis.readutf ())!=null) {System.out.println ("Server:" +message); Receive and output information from the server}dis.close ();d os.close (); S.close ();} catch (Connectexception ex) {ex.printstacktrace ();} catch (IOException ex) {ex.printstacktrace ();}}}
Execution Result:
Client:
Service side:
The whole process of connecting and interacting, such as:
When executed, start the server side, the service side creates the socket ServerSocket and binds to the specified port, when executed to socket s=ss.accept (), will produce "blocking" (that is, let the program temporarily stay here), but the client starts, When a socket socket is created and a request is sent to a specified port on the specified address, ServerSocket accepts the server's request and returns the client's socket instance to establish a connection with it. socket intended for the socket, but also really very image, the whole process is like the client plug into the service end of the socket, the establishment of the channel. After the communication is complete, both sides close the connection.
In the example, the socket's getInputStream () method can obtain a network connection input that returns the byte input stream object of this socket, and the Getoutputstream () method returns the byte output stream object for this socket, which is used to write data to the connection object. This reflects the third feature of TCP above, " byte-based streaming ".
UDP protocol-based communication
service-side code:
import Java.net.*;class udpserver{public static void Main (string[] args) throws exception{//receive information datagramsocket SE RVer = new Datagramsocket (5050); byte[] Recvbuf = new byte[1000]; Datagrampacket recvpacket = new Datagrampacket (recvbuf, recvbuf.length); Server.receive (Recvpacket); String recvstr = new String (Recvpacket.getdata (), 0, Recvpacket.getlength ()); SYSTEM.OUT.PRINTLN ("What servers have received is:" + recvstr); Send Message int port = Recvpacket.getport (); InetAddress addr = recvpacket.getaddress (); String sendstr = "Hello!" I ' m Server "; byte[] SendBuf = new String ("Hello client! I ' m server! "). GetBytes (); Datagrampacket sendpacket = new Datagrampacket (SendBuf, sendbuf.length, addr, port); Server.send (Sendpacket); Server.close (); }}
Client code:
Import java.net.*;class udpclient{public static void Main (string[] args) throws exception{ //Send Message Datagramsocket client = new Datagramsocket (); Byte[] sendbuf=new String ("Hello server! I ' m Client "). GetBytes (); InetAddress addr = Inetaddress.getbyname ("127.0.0.1"); int port = 5050; Datagrampacket sendpacket = new Datagrampacket (SendBuf, Sendbuf.length, Inetaddress.getbyname ("127.0.0.1"), port ); Client.send (sendpacket); Receive information byte[] recvbuf = new byte[100]; Datagrampacket recvpacket = new Datagrampacket (recvbuf, recvbuf.length); Client.receive (recvpacket); String recvstr = new String (Recvpacket.getdata (), 0, Recvpacket.getlength ()); SYSTEM.OUT.PRINTLN ("What client had received is:" + recvstr); Client.close (); }}
The whole process is as follows:
After the server is started, a datagram packet containing byte array buf is prepared Datagrampacket is used to receive the datagram sent by the client, and after the client starts, the destination address, port, sending content and other information are encapsulated in Datagrampacket. The Datagramsocket Send () method is sent to the destination (the server side), and the server receives the datagram in Datagrampackage. The process of sending datagrams to the client is the same as the server.
Introduction to J2SE Fast Advanced--socket Programming (TCP/UDP)