public class Server {
public static void Main (string[] args) {
Socket Socket=null;
BufferedReader Br=null;
PrintWriter Pw=null;
try {
Create a server and open 3081 ports
ServerSocket server=new ServerSocket (3081);
while (true) {
Listen to the server port and, once the data is sent, encapsulate the data as a socket object.
If no data is sent, then it is in a thread-blocking state and does not continue down execution.
Socket=server.accept ();
SYSTEM.OUT.PRINTLN ("Client Information:" +socket.getremotesocketaddress ());
Gets the read stream from the socket, which has the data sent by the client.
InputStream In=socket.getinputstream ();
InputStreamReader byte flow into a character stream
Br=new BufferedReader (New InputStreamReader (in));
Row Read client data
String Info=br.readline ();
SYSTEM.OUT.PRINTLN (info);
OutputStream Out=socket.getoutputstream ();
Pw=new PrintWriter (out);
PW.PRINTLN ("The server said: I beat you to death");
Pw.flush ();
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
try {
Pw.close ();
Br.close ();
Socket.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
public class Client {
public static void Main (string[] args) {
Socket Socket=null;
PrintWriter Pw=null;
BufferedReader Br=null;
try {
Create a socket object and indicate the IP address and port number of the server
Socket=new Socket ("localhost", 3081);
Get the output stream of the socket sending data
OutputStream Out=socket.getoutputstream ();
Wrap a byte stream into a character stream
Pw=new PrintWriter (out);
Sending data to the server
PW.PRINTLN ("client says: Army-burning");
Refresh the stream to ensure that the data can be written to the server
Pw.flush ();
InputStream In=socket.getinputstream ();
Br=new BufferedReader (New InputStreamReader (in));
String Info=br.readline ();
SYSTEM.OUT.PRINTLN (info);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
finally{
try {
Pw.close ();
Socket.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
ServerSocket and sockets