Zhao yazhi _ java Network Programming (2) TCP

Source: Internet
Author: User

TCP: Client Server

Server:

ServerSocket: Write a TCP network service program. First, use the java.net. ServerSocket class to create a server Socket.

Constructor:

ServerSocket (int port): Creates a server socket bound to a specific port.
ServerSocket (int port, int backlog): Creates a server socket and binds it to the specified local port number by using the specified backlog (the number of customers waiting for the connection request to be established during busy hours.
ServerSocket (int port, int backlog, InetAddress bindAddr): Creates a server using the specified port, listener backlog, and local IP address to bind.
Common Methods:

Socket accept (): listens and is connected to this Socket.
Boolean isBound (): returns the binding status of ServerSocket.
InetAddress getInetAddress (): returns the local address of the server socket.
Boolean isClosed (): returns the shutdown status of ServerSocket.
Void close (): close this socket.
Void bind (SocketAddress endpoint): bind ServerSocket to a specific address (IP address and port number ).
Client:

Socket: to establish a connection between the client and the server, you must first create a Socket object.

Common Constructor

Socket (String host, int port): Creates a stream Socket and connects it to the specified port number on the specified host.
Socket (InetAddress address, int port): Creates a stream Socket and connects it to the specified port number of the specified IP address.
Common Methods

InetAddress getInetAddress (): return the socket connection address.
Int getPort (): return the remote port to which the socket is connected.
InetAddress getlocalAddress (): gets the local address bound to the socket.
Int getLocalPort (): returns the local location to which the socket is bound.
Void close (): returns the input stream of this socket.
InputStream getInputStream (): returns the input stream of this socket.
OutputStream getOutputStream (): return the output stream of this socket.
The server program calls the accept () method in the ServerSocket class to wait for the client connection request. Once accept () receives the client connection request, this method returns a Socket object that establishes a leased line connection with the client. You do not need to use a program to create this Socket object. The two sockets with established connections exchange data in the form of IO streams. Java provides the getInputStream () in the Socket class to return the input stream object of the Socket, getOutputStream () return the output stream object of the Socket.


Start the service first and then start the client)

Otherwise, the following error occurs:

 

 

Instance 1: client and server

Client:

[Java]
Package src.com.hbsi.net;
 
Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. Socket;
 
Public class TcpClient {
 
/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
// 1. Establish a tcp client socket. Determine the ip address and port of the server to be connected.
Socket s = new Socket ("192.168.49.59", 9009 );

// 2. Obtain the output stream object through the established socket
OutputStream out = s. getOutputStream ();

Out. write ("wo lai le". getBytes ());

// Read the information sent from the server
InputStream in = s. getInputStream ();

Byte [] buf = new byte [1, 1024];

Int len = in. read (buf );
System. out. println (new String (buf, 0, len ));

S. close ();
}
 
}

Package src.com.hbsi.net;

Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. Socket;

Public class TcpClient {

/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
// 1. Establish a tcp client socket. Determine the ip address and port of the server to be connected.
Socket s = new Socket ("192.168.49.59", 9009 );

// 2. Obtain the output stream object through the established socket
OutputStream out = s. getOutputStream ();

Out. write ("wo lai le". getBytes ());

// Read the information sent from the server
InputStream in = s. getInputStream ();

Byte [] buf = new byte [1, 1024];

Int len = in. read (buf );
System. out. println (new String (buf, 0, len ));

S. close ();
}

}

Server

[Java]
Package src.com.hbsi.net;
 
Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. ServerSocket;
Import java.net. Socket;
 
Public class TcpServer {
 
/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
// 1. Create a server socket

ServerSocket ss = new ServerSocket (9009 );
// 2. Call accept ()
Socket s = ss. accept ();

String ip = s. getInetAddress (). getHostAddress ();
System. out. println (ip + "... connection ");

InputStream in = s. getInputStream ();
Byte [] buf = new byte [1, 1024];
Int len = in. read (buf );

System. out. println (new String (buf, 0, len ));

// The server returns information to the client.
OutputStream out = s. getOutputStream ();
Out. write ("wo shou dao le". getBytes ());

S. close ();
Ss. close ();


 
}
 
}

Package src.com.hbsi.net;

Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. ServerSocket;
Import java.net. Socket;

Public class TcpServer {

/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
// 1. Create a server socket

ServerSocket ss = new ServerSocket (9009 );
// 2. Call accept ()
Socket s = ss. accept ();

String ip = s. getInetAddress (). getHostAddress ();
System. out. println (ip + "... connection ");

InputStream in = s. getInputStream ();
Byte [] buf = new byte [1, 1024];
Int len = in. read (buf );

System. out. println (new String (buf, 0, len ));

// The server returns information to the client.
OutputStream out = s. getOutputStream ();
Out. write ("wo shou dao le". getBytes ());

S. close ();
Ss. close ();

}

}
Open in the CMD command window:

 

 

Instance 2: clients and servers that can be input from the keyboard

Client:

[Java]
Package src.com.hbsi.net;
 
Import java.net. Socket;
Import java. io .*;
 
Public class TcpClient2 {
 
/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {

Socket s = new Socket ("192.168.49.59", 9009 );
// Obtain keyboard input
BufferedReader br = new BufferedReader (new InputStreamReader (System. in ));
// Output data to the server
OutputStream out = s. getOutputStream ();

BufferedWriter bwout = new BufferedWriter (new OutputStreamWriter (out ));
// Obtain the data returned by the server
BufferedReader brin = new BufferedReader (new InputStreamReader (s. getInputStream ()));

String line = null;

While (line = br. readLine ())! = Null ){
If (line. equals ("over "))
Break;

Bwout. write (line );
Bwout. newLine ();
Bwout. flush ();

String str = brin. readLine ();
System. out. println ("server:" + str );


}
Br. close ();
S. close ();
 
}
 
}

Package src.com.hbsi.net;

Import java.net. Socket;
Import java. io .*;

Public class TcpClient2 {

/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {

Socket s = new Socket ("192.168.49.59", 9009 );
// Obtain keyboard input
BufferedReader br = new BufferedReader (new InputStreamReader (System. in ));
// Output data to the server
OutputStream out = s. getOutputStream ();

BufferedWriter bwout = new BufferedWriter (new OutputStreamWriter (out ));
// Obtain the data returned by the server
BufferedReader brin = new BufferedReader (new InputStreamReader (s. getInputStream ()));

String line = null;

While (line = br. readLine ())! = Null ){
If (line. equals ("over "))
Break;

Bwout. write (line );
Bwout. newLine ();
Bwout. flush ();

String str = brin. readLine ();
System. out. println ("server:" + str );


}
Br. close ();
S. close ();

}

}

Server:

[Java]
/* The client enters information on the keyboard and sends it to the server.
After receiving the information, the server converts it into uppercase and returns it to the client. */
 
 
 
Package src.com.hbsi.net;
 
Import java. io. BufferedReader;
Import java. io. BufferedWriter;
Import java. io. InputStream;
Import java. io. InputStreamReader;
Import java. io. OutputStreamWriter;
Import java.net. ServerSocket;
Import java.net. Socket;
 
Public class TcpServer2 {
 
/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
ServerSocket ss = new ServerSocket (9009 );

Socket s = ss. accept ();

System. out. println (s. getInetAddress (). getHostAddress () + "... connection ");
// Read the input stream of customer information
InputStream in = s. getInputStream ();

BufferedReader brin = new BufferedReader (new InputStreamReader (in ));
// Send the information output stream to the client
BufferedWriter brout = new BufferedWriter (new OutputStreamWriter (s. getOutputStream ()));

String line = null;

While (line = brin. readLine ())! = Null ){
System. out. println ("client:" + line );

Brout. write (line. toUpperCase ());
Brout. newLine ();
Brout. flush ();

}
S. close ();
Ss. close ();
 
}
 
}

/* The client enters information on the keyboard and sends it to the server.
After receiving the information, the server converts it into uppercase and returns it to the client. */

 

Package src.com.hbsi.net;

Import java. io. BufferedReader;
Import java. io. BufferedWriter;
Import java. io. InputStream;
Import java. io. InputStreamReader;
Import java. io. OutputStreamWriter;
Import java.net. ServerSocket;
Import java.net. Socket;

Public class TcpServer2 {

/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
ServerSocket ss = new ServerSocket (9009 );

Socket s = ss. accept ();

System. out. println (s. getInetAddress (). getHostAddress () + "... connection ");
// Read the input stream of customer information
InputStream in = s. getInputStream ();

BufferedReader brin = new BufferedReader (new InputStreamReader (in ));
// Send the information output stream to the client
BufferedWriter brout = new BufferedWriter (new OutputStreamWriter (s. getOutputStream ()));

String line = null;

While (line = brin. readLine ())! = Null ){
System. out. println ("client:" + line );

Brout. write (line. toUpperCase ());
Brout. newLine ();
Brout. flush ();

}
S. close ();
Ss. close ();

}

}


 

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.