I learned the class set framework two days ago and went around it a bit. So let's take a look at socket programming and try it ....
This is the most basic one-to-one socket. The server can only "link" with one client "... After compiling and running the server, the program blocks and waits for client connection. After the client is compiled and run, it connects to the local server and waits for the user to input information. The information is sent to the server and printed and output on the server. At the same time, the server returns a message to the client. When the client inputs end, both programs exit.
This is a server program.
| The code is as follows: |
Copy code |
|
Import java. io .*;
Import java.net .*;
Public class server {
Public static void main (String [] args) throws Exception {// The declaration throws an Exception.
// Create a socket instance for the server
ServerSocket server = new ServerSocket (2345 );
// Block the connection to the listening port. If there is a connection, create a socket instance.
Socket client = server. accept ();
// Declare the receiving (input stream) instance to receive data from the client
BufferedReader read = new BufferedReader (new InputStreamReader (client. getInputStream ()));
// Declare that the sending (output stream) instance sends data to the connected client
PrintWriter write = new PrintWriter (client. getOutputStream ());
// Unlimited execution requests
While (true ){
// Listen for received information from the client. If yes, read a row.
String str = read. readLine ();
System. out. println ("received from the client:" + str );
// Send information to the socket client
Write. println ("This is from the server:" + str );
Write. flush (); // refresh the output buffer
// Exit if end is received.
If (str. equals ("end") break;
}
Write. close (); // close sending
Read. close (); // close the Receiving
}
} |
This is a client program.
| The code is as follows: |
Copy code |
|
Import java. io .*;
Import java.net .*;
Public class client {
Public static void main (String [] arsg) throws Exception {
// Create a client instance
Socket client = new Socket (InetAddress. getLocalHost (), 2345 );
// Declare to receive (input stream)
BufferedReader read = new BufferedReader (new InputStreamReader (client. getInputStream ()));
// Send a declaration (output stream)
PrintWriter write = new PrintWriter (client. getOutputStream ());
// Declare the keyboard input stream
BufferedReader kbread = new BufferedReader (new InputStreamReader (System. in ));
While (true ){
// Obtain a line of input from the keyboard
String str = kbread. readLine ();
// Send
Write. println (str );
Write. flush ();
If (str. equals ("end") break;
System. out. println (read. readLine (); // get a return
}
System. out. println ("Exit the connection! ");
Read. close ();
Write. close ();
}
} |