Service-Side Authoring steps:
Using ServerSocket to establish a port for the service port monitoring;
Using the Accept method to wear a service-side socket
Create an input-output stream with an established socket
Close the input/output stream close the socket shutdown server
public class Server {
Public Server () {
try {
ServerSocket Server = new ServerSocket (8090);
SYSTEM.OUT.PRINTLN ("Server started, waiting for client requests ...");
while (true) {
Socket socket = server.accept ();//Listen for client requests
The server receives the client's request
InputStream in = Socket.getinputstream ();
Byte[] by = new byte[1024];
In.read (by);
SYSTEM.OUT.PRINTLN ("Server side received request information from client:" + new String (by). Trim ());
Server response information returned to the client
OutputStream out = Socket.getoutputstream ();
Out.write ("Hello". GetBytes ());
In.close ();
Out.close ();
Socket.close ();
Server.close ();
//}
} catch (IOException e) {
E.printstacktrace ();
}
}
public static void Main (string[] args) {
New Server ();
}
}
Client Authoring Steps
Create a client socket to initiate a connection request to the server
Create an input-output stream with an established socket
Close the socket shutdown server by closing the input/output stream
public class Client {
Public Client () {
try {
String input_info = Joptionpane.showinputdialog (null, "Please enter request Information");
Socket socket = new Socket ("127.0.0.1", 8090);
The client sends a request to the server
OutputStream out = Socket.getoutputstream ();
Out.write (Input_info.getbytes ());
Response from client Receiving server
InputStream in = Socket.getinputstream ();
byte [] b = new byte[1024];
System.out.println (b.length);
In.read (b);
SYSTEM.OUT.PRINTLN ("Client receives server-side response information:" + new String (b). Trim ());
Out.close ();
In.close ();
Socket.close ();
} catch (Unknownhostexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
public static void Main (string[] args) {
New Client ();
}
}
2016.3.19 (Java Network programming)