What is socket
The two programs on the network implement data exchange through a two -way communication connection. One end of this two -way link is called a socket. Socket is usually used to achieve connection between the customer and the service party. Socket is a very popular programming interface of the TCP/IP protocol, and a socket is determined by an IP address and a port number.
However, the types of protocols supported by Socket are not only TCP/IP, so there is no necessarily connection between the two. In the Java environment, Socket programming mainly refers to network programming based on the TCP/IP protocol.
The process of socket communication
Whether the Server end Listen (monitor) has a connection request, the Client sends a Connect request to the Server side, and the server sends back the access message to the client. A connection is established. Both the server and the client can communicate with the other party through Send, WRITE and other methods.
For a full -featured socket, the following basic structures must be included. The work process contains the following four basic steps:
(1) Create a socket;
(2) Open the input/outflow connected to the socket;
(3) Read/write operation of the socket according to a certain protocol;
(4) Turn off the socket. (In practical applications, the displayed Close is not used. Although many articles are recommended, in my program, it may be because the program itself is relatively simple and the requirements are not high, so it does not cause anything to cause anything. Influence.)
Create socket
Java provides two types of sockets and Serversockets in Java.net, which are used to represent the client and server of two -way connection. These are two very good classes that are very good, which is convenient to use. The structure method is as follows:
Socket (indaddress address, int port); socket (indaddress address, int port, boolean stream); Socket (String Host, INT PROT); OT, Boolean Stream); Socket (SocketIMPL IMPL) Socket (String Host, int Port, INTADDDRESS LOCALADDR, Int Localport) Socket (INETADDDRESS Address, INTADDDDRESS LOCALDDR, INT LOCALPORT) Serversocket (INT PORT). ; Serversocket (int port, int Backlog); Serversocket (int port, INTADDDDRESS BINDDDR Cure
Among them, the IP address, host name and port number of the other party in the two -way connection, respectively. Stream indicates whether the socket is a stream Socket or a data newspaper Socket. LocalPort represents the port number of the local host. Serversocket's host address), IMPL is the parent class of the socket, which can be used to create a Serversocket and can be used to create a socket. Count means the maximum number of connections that the server can support. For example: Learning Video Network http://www.xxspw.com
Socket client = New Socket
Note that when selecting a port, you must be careful. Each port provides a specific service. Only by giving the correct port can we get the corresponding service. The port number of 0 ~ 1023 is reserved by the system. For example, the port number of the HTTP service is 80, the port number of the Telnet service is 21, and the port number of the FTP service is 23, so when we choose the port number, it is best to choose one greater than 1023. The number is to prevent conflicts.
If an error occurs when creating a socket, IOEXCEPTION will be generated, and it must be processed in the program. Therefore, creating a socket or serverSocket must be captured or thrown.
Code
server
Package Socket; Import Java.io.*; Import Java.net.*; Public Class TCPSERVER {Public Static Void Main (String [] ARGS) Throws Exception {Serves Ket server = new serverSocket (9091); try {socket client = server. Accept (); Try {bufferedReader input = new bufferedReader (new inputStreamReader (client.getInputStream ())); Boolean Flag = TRUE; int LAG) {system.out.println ("The client wants to start sending Sao, this is the " + count +" times! "); Count ++; String line = input.readline (); System.out.println (" Client said: " + line); if (" Line.equals (" exit ")) {flag = false; system.out.println (" The client doesn't want to play anymore! ");} else {system.out.println (" client said: " + line);}} Finally {client {client {client .close ();}} Finally {server.close ();}}}
client
Package socket; Import Java.io.*; Import Java.net.*; Import Java.util.Scanner; Public Class TCPClient {Public Static Void Main (String [] ARGS). Throws Exception {Socket Client = New Socket ("127.0. 0.1 ", 9091); TRY {Printwriter Output = New Printwriter (Client.getputstream (), TRUE); Scanner Cin = New Scanner (System.in); string words; While (CIN.H asnext ()) {words = cin. nextLine (); output.println (words); system.out.println ("write data:" + words);} cin.close ();} Finally {client.close ();}}}}}}}}}}}}Server binding IP
When writing sockets with C, the Struct Sockaddr_IN structure can specify SIN_ADDR.S_ADDR, that is, you can specify the IP address. Why is there such a demand? For example, my network link is:
I may just want to bind the IP address of the ETH0 network card, because my LO and WLAN0 may be using a nginx virtual host with one port. Therefore, when the server is opened on the server, there is a need for specified IP.
plan
A constructor of the serverSocket is as follows:
Public Serversocket (Int Port, INTADDDDRESS BINDDDR) Throws IOEXception
parameter:
Port -Local TCP port
backlog -listening to Backlog
bindaddr -to be binded by the server
Because the InetadDress has no constructor, I have been tangled here for a while. Check on Stackoverflow, you can use the getByname method of Inetaddress
For example code
Indadress bindip = INetaddress.getByname ("192.168.1.168"); Serversocket Server = New Serversocket (9091, 0, Bindip); Concurrent access
The server handles multiple clients by adding multi -threaded requests at the same time. In fact, the implementation is still very water. After all, Java is good enough for multi -threaded packaging. Methods to handle the client's request and print out the data
Server code
Package CapitalSocket; Import Java.io.BufferedReader; Import Java.io.ioException; Import Java.Io.inputStreamReader; Import Java.net.ineTadDress ; Import java.net.serversocket; Import Java.net.socket; Public Class CapitalizeServer {PRIVATE Static int Clientnum = 0; Public Static Void Main (String ARGS []) Throws Exception {Serversocket Listener = New Serversocket me ("192.168.1.168"); Try {While (TRUE) {Capitalizer Multip = New Capitalizer (Listener.Accept (), CapitalizeServer.clientnum ++); Thread T = New Thread (Multip); T.Start ();} Finally {Listener.close (); } PRIVATE Static Capitalizer Implements Runnable {Private Socket Client; Private int ID; Public Capitalizer (Socket S, int ID) {this.client = s; this.id = id;} public void () {try {buffer EDREADER Input = New BufferedReader (New InputStreamReamReader (this .client.getInputStream ())); While (true) {string data = input.readline (); if (data.equals ("bye") {system.out.println ("Current" + This.id + + "I don't want to play a client!"); Break;} else {system.out.println ("Current" + this.id + "client said:" + data); ) {e.printstacktrace ();} Finally {try {This.client.close ();} Catch (IOEXCEPTION E) {e.printstacktrace ();}}}}}}}}}}}}
Client code client code has basically not changed, adding an exit operation
Package CapitalSocket; Import Java.io.printwriter; Import Java.net.socket; Import Java.util.Scanner; Public Class CapitalizeClient {Public Static Void Main (String [] args) Throws Exception {Socket Client = New Socket ("192.168. 1.168 ", 9898); TRY {Printwriter Output = New Printwriter (Client.GetoutPutstream (), TRUE); Scanner Cin = New Scanner (System.in); string words; While (CIN .hasnext ()) {words = cin. Nextline (); output.println (words); if (words.equals ("bye") {break;} // Every time you write data, you need to be thread.sleep (3000);} cin.close (); } finally {client.close ();}}}}