Java implementation based on TCP network programming steps __ Programming

Source: Internet
Author: User
Tags serialization

Reference Java Programming Tutorial (second Edition) Yong Junhai's book 12 chapters

The establishment of a server-side program design model usually consists of the following five steps:

(1) On the server side, first create the ServerSocket instance object, register the port number to connect on the server side, and the maximum number of clients allowed to connect.

(2) Call the ServerSocket member method accept to wait and listen for connections from the client. When a client establishes a connection to the server side, the member method of the class ServerSocket accept returns the socket on the server side of the connection channel. The socket is the type of socket through which data communication can be made with the client.

(3) To invoke the member method of the class socket getInputStream and Getoutputstream to obtain the input stream (InputStream) and output stream (OutputStream) corresponding to the socket. Serialization is required when using a socket network to transfer objects.

(4) Data communication with the client through the obtained input stream and the output stream, and processing information obtained from the client and the data to be sent to the client.

(5) After the data communication completes, closes the input stream, the output stream and the socket (socket).

After the instance object of the class ServerSocket is created on the server side and the member method accept of the class ServerSocket is invoked, the server side begins to wait for the client to connect to it.

The establishment of a client-side program design model usually consists of the following four steps:

(1) At the client, create an instance object of the socket and establish a connection with the server side. When creating an instance object for a socket, you need to set the server-side hostname and the port number for the connection, that is, the port number that is registered when the class ServerSocket instance object is constructed on the server-side. The host name and the port number exactly match to establish a connection and construct an instance object for the socket of the class. The steps after constructing the instance object of the class socket are basically consistent with the corresponding steps on the server side.

(2) to invoke the member method of the class socket getInputStream and Getoutputstream to obtain the input stream (InputStream) and output stream (OutputStream) corresponding to the socket. Serialization is required when using a socket network to transfer objects.

(3) Data communication with the client through the obtained input stream and output stream, and processing of the information obtained from the server side and the data to be sent to the server side.

(4) After the data communication completes, closes the input stream, the output stream and the socket (socket).

Server, using ServerSocket to listen to the specified port, the port can be arbitrarily specified (because the port under 1024 is usually reserved port, in some operating systems are not free to use, so it is recommended to use a port greater than 1024), waiting for customer connection request, after the client connected, the session generated , and close the connection after the session completes.
Client, use the socket to issue a connection request to a port on one of the servers on the network, open the session once the connection is successful, and close the socket after the session completes. The client does not need to specify an open port, typically temporarily, dynamically allocating more than 1024 ports.

c/S mode socket Connection diagram:

Example

(1) server-side single message to the client, the client received a message, the end of a communication, the client program ended, and the server side continues to wait for the next client connection. To terminate the program, press CTRL +c at the same time on the console.

The results are shown below:


The code is as follows

Server side:

Package WJL;

Import Java.io.DataOutputStream;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;


public class J_server
{public
	static void Main (string[] args)
	{
		int port = 8083;
		try{
		ServerSocket Server = new ServerSocket (port);
		while (true)
		{
		Socket client = Server.accept ();
		SYSTEM.OUT.PRINTLN ("Server-side connection received from client");
		
		OutputStream o = Client.getoutputstream ();
		DataOutputStream d = new DataOutputStream (o);
		D.writeutf ("Hello to client on server side");//writeutf () writes two byte length information to the output stream, followed by the utf-8 representation of each character in the modified string.
		d.close ();
		O.close ();		
		}
		catch (Exception e)
		{
			e.printstacktrace ();
		}
		
	}

}

Client

Package WJL;

Import Java.io.DataInputStream;
Import Java.io.InputStream;
Import Java.net.Socket;


public class J_client
{public
	static void Main (string[] args)
	{
		int port = 8083;
		Try
		{
			Socket client = new Socket ("localhost", port);
			InputStream o = Client.getinputstream ();
			DataInputStream d = new DataInputStream (o); 
			SYSTEM.OUT.PRINTLN ("Client Received:" + D.READUTF ());//readutf () reads the characters in the input stream encoded in UTF format and returns a string.
			d.close ();
			O.close ();
		}
		catch (Exception e)
		{
			//Todo:handle Exception
			e.printstacktrace ();
		}
	}

}

(2) server-side and client can send and receive messages, but after a communication, both server-side and client run the end.

The results are shown below:


Server-side

Package WJL;
Import Java.io.BufferedOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;

Import Java.net.Socket; Class WebServer {public static void main (string[] args) {int port = 9999;/* to open a port is to open a service the allocation of---ports must be unique because the port is for the sole  The * port number that identifies the unique service for each computer is from 0~65535, the first 1024 ports have been TCP/IP as the reserved port, so the port you are allocating can only be 1024 after the */try {serversocket Server = New ServerSocket (port);//create server-side socket Socket client = server.accept ();//listener. Server-side to establish its own socket outputstream o = Client.getoutputstream ()//server-side to open its own output stream Bufferedoutputstream B = new Bufferedoutputstre AM (o);//Use the cached output stream InputStream i = client.getinputstream ()//server-side to open its own input stream O.write ("Hello,i AM Server". GetBytes ())
		//server hello,i AM server writes output stream-client B.write ("Hello,i AM Server". GetBytes ());

		B.flush (); byte[] buf = new byte[100];//The character stream of the server-side output stream read in the storage socket channel int len = I.read (BUF);//read (byte[] b) is read from the current server-side input flow (that is, the client's output stream) and stored to
		Character array buf, the method returns the length of the character array that is read out. System.out.println (New String (Buf,0,len));//Client-"server."
		New String (Buf,0,len) is a string of characters that buf a character array from subscript 0 to Len//system.out is a java.io.OutputStream type variable o.close ();//server-side shutdown output stream
		B.close (); I.close ()//client closes the input stream Client.close ()//client closes socket server.close ();/server closes socket} catch (Exception e) {/TODO Auto
		-generated Catch block E.printstacktrace ();
 }

	}
}

Client

Package WJL;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.InetAddress;
Import Java.net.Socket;

public class WebClient 
{public
	static void Main (string[] args) 
	{
		int port=9999;
		try{
		Socket client = new socket (inetaddress.getbyname ("localhost"), port);//Create client End socket
		// InetAddress---Represents the Internet Protocol (IP) address  ---inetaddress.getbyname ("www.163.com")--Determine the IP address of the host, given the hostname--if the parameter is NULL, Obtain the native IP address
		outputstream o = Client.getoutputstream ();//Open the client's output stream
		inputstream i = Client.getinputstream () ;//Open the input stream of the client
		byte[] buf = new byte[100];
		int len = I.read (BUF);
		System.out.println (New String (Buf,0,len));//server-client
		
		o.write ("Hello,i am Client". GetBytes ());/Client hello,i AM The client writes to the output stream-server. Write (byte[] b) writes the bytes of byte array B to the current file.
		o.close ()//Close the client's output stream
		i.close ()//Close the client's input stream
		client.close ();//close socket
		}
		catch (Exception e)
		{
			e.printstacktrace ();
			
		}

	}
}


Related Article

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.