Socket class ---- implement client Socket
---- Sockets are the endpoints for communication between two machines. They are used to describe IP addresses and ports. applications usually send requests to or respond to network requests through sockets.
---- Constructor: Socket (InetAdress address, int port) --- creates a stream Socket and connects it to the port number of the specified IP address.
Simulate a client
[Java]
Package guo;
Import java. io. BufferedReader;
Import java. io. InputStreamReader;
Import java. io. OutputStreamWriter;
Import java. io. PrintWriter;
Import java.net. Socket;
Public class Client1 {
Public static void main (String [] args)
{
Try
{
Socket socket = new Socket ("127.0.0.1", 8000 );
BufferedReader in = new BufferedReader (new InputStreamReader (System. in ));
PrintWriter out = new PrintWriter (new OutputStreamWriter (socket. getOutputStream (), true );
BufferedReader in1 = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
While (true)
{
/* Read a row from the keyboard */
String str = in. readLine ();
If (str = null | "". equals (str) break;
/* Write to the server */
Out. println (str );
String str1 = in1.readLine ();
System. out. println (str1 );
}
Socket. close ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
}
}
Simulate Server
[Java]
Package guo;
Import java. io. BufferedReader;
Import java. io. InputStreamReader;
Import java. io. OutputStreamWriter;
Import java. io. PrintWriter;
Import java.net. ServerSocket;
Import java.net. Socket;
Public class Service1 {
Public static void main (String [] args)
{
Try
{
/* Opening a port is to enable a service. The port allocation must be unique because the port is used to uniquely identify the unique service of each computer.
* The port number ranges from 0 ~ The first 65535 ports are reserved by TCP/IP. Therefore, the allocated ports can only be ports later than 1024 */
ServerSocket s = new ServerSocket (8000 );
System. out. println ("the service has been enabled. Wait for the customer to access it! ");
/* Wait for the customer to access the service. If there is no customer, the service will be blocked */
Socket socket = s. accept ();
System. out. println ("access received from the customer! ");
/* The server reads data from the Socket input stream */
BufferedReader in = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
BufferedReader in1 = new BufferedReader (new InputStreamReader (System. in ));
PrintWriter out = new PrintWriter (new OutputStreamWriter (socket. getOutputStream (), true );
While (true)
{
// Read data from the socket input stream
String str = in. readLine ();
If ("exit". equals (str) break;
/* Print it to the console */
System. out. println (str );
/* Server-side keyboard */
String str1 = in1.readLine ();
Out. println (str1 );
}
Socket. close ();
S. close ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
}
}