Java Learning TCP network programming, socket use

Source: Internet
Author: User

ServerSocket This class implements a server socket. ServerSocket commonly used in the construction methods are as follows,

ServerSocket ()
Create a non-binding server socket.

ServerSocket (int port)
Creates a server socket bound to a specific port.

ServerSocket (int port, int backlog)
Creates a server socket with the specified backlog and binds it to the specified local port number.

ServerSocket (int port, int backlog, inetaddress bindaddr)
Creates a server using the specified port, the listener backlog, and the local IP address to bind to.

Socket This class implements a client socket (which can also be called a "socket"). Socket class commonly used in the construction methods have the following
Socket ()
Create an SocketImpl socket from the system default type

Socket (inetaddress address, int port)
Creates a stream socket and connects it to the specified port number for the specified IP address.

Socket (inetaddress address, int port, inetaddress localaddr, int localport)
Creates a socket and connects it to the specified remote port on the specified remote address.

Socket (proxy)
Creates an disconnected socket and specifies the proxy type, if any, that should be used regardless of the other settings.

Socket (SocketImpl impl)
Creates a non-connected Socket using the user-specified SocketImpl.

Socket (String host, int port)
Creates a stream socket and connects it to the specified port number on the specified host.

Socket (String host, int port, inetaddress localaddr, int localport)
Creates a socket and connects it to the specified remote port on the specified remote host.

The methods commonly used in these two classes are
getInputStream ()
Returns the input stream that inputstream this socket.
Getoutputstream ()
Returns the output stream that outputstream this socket.

JAVA in the use of TCP protocol to communicate the application is the primary and secondary points, a service-side, called the client, the two functions are not written in the same way,
The server uses the ServerSocket and socket classes, and the client uses a socket.
The process of interacting between them is roughly as follows:
1. The service-side program first creates a serversocket and then calls the Accept () method of the class, listening for and accepting connections to this socket.
2. The client program creates a socket and requests a connection to the server.
3, the server receives a connection request from the client, the Accept () method returns a socket object and obtains the data from the client.

When using the Accept () method of the service-side ServerSocket If the data is heard, the socket object returned is the client with the requested connection.
Socket, where the OutputStream object obtained by the server socket object is the InputStream object of the client socket object, and
The InputStream object obtained by the server-side socket object is the OutputStream object of the client socket object, where the input-output stream object is relative
And that's. It's like making a phone call, what you hear inside your earpiece is what someone else says, and when you talk inside the mic,
Others hear what you are talking about in his earpiece.
Unlike the UDP protocol, the TCP protocol is a reliable connection protocol, and TCP guarantees data correctness when it is sent from one end to the other.
and the order of the received data is the same as the data sent out. The data sent by the UDP protocol can be lost, or the order may not necessarily be issued by
In the same order. The TCP protocol is suitable for those situations where reliability requirements are high. You should look at the use cases to decide whether to use TCP or UDP

TCP Network Programming If you do not involve too many other services, it is just back and forth between the server and the client data, in fact, it is quite simple.
Here is a simple example code, one of which is the client, and one is the code for the server's program

//The first is the service-sideimport java.io.*; import java.net.*; Public classServer { Public Static voidMain (string[] args) throws Exception {//Create a server socket that is bound to a specific port 10000. ServerSocket ServerSocket =NewServerSocket (10000); System. out. println ("Server is open"); //listens for and accepts client connections that correspond to this socket. Socket socket =serversocket.accept (); //get input Stream objectInputStreaminch=Socket.getinputstream (); byte[] buf =New byte[1024x768]; intLen =inch. Read (BUF); String InData=NewString (BUF,0, Len); String IP=socket.getinetaddress (). gethostaddress (); System. out. println ("Client data is:"+ InData +"And IP is:"+IP); //gets an output stream objectOutputStream out=Socket.getoutputstream (); //write the information to the output stream         out. Write ("Hi Client I had got you message yeah!". GetBytes ()); //Close ObjectSocket.close ();    Serversocket.close (); }}

//Next, this is the client code.import java.io.*; import java.net.*; Public classClient { Public Static voidMain (string[] args) throws Exception {//create a flow socket and connect it to the specified port number 10000 on the 127.0.0.1. Socket socket =NewSocket ("127.0.0.1",10000); //get an output streamOutputStream out=Socket.getoutputstream (); //writes the data to the output stream, without explicit data-sending methods, because once the server is connected//The connection is valid until the socket is closed, and the data can be inputstream on the server         out. Write ("Hi Server,this is client.how.". GetBytes ()); //get an input stream to fetch the information sent from the server.InputStreaminch=Socket.getinputstream (); byte[] buf =New byte[1024x768]; intLen =inch. Read (BUF); String InData=NewString (BUF,0, Len); System. out. println ("The Server back message is:"+inData);    Socket.close (); }}

The above code can be used directly, you can see, if it is simply connected to the server and the client, the classes and methods involved are not many, and more simple than UDP, but the input and output stream is a bit difficult to understand, but write a few more.

Java Learning TCP network programming, socket use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.