1. Server-side
1. Create a ServerSocket object to specify the listening port in the constructor;
private int port = 8000;
private ServerSocket serverSocket;
……
serverSocket = new ServerSocket(port);
2. Server-side invoke the Accept () method of the ServerSocket object, which listens on the port, waits for a client's connection request, and if a connection request is received, the Accept () method returns a Socket object. This socket object will form a communication line with the client's socket object;
Socket socket = null;
socket = serverSocket.accept(); // 等待客户连接
The 3.Socket class provides the getInputStream () method and the Getoutputstream () method.
InputStream socketin = Socket.getinputstream ();
OutputStream socketout = Socket.getoutputstream ();
Source Code Echoserver.java
public class Echoserver {
private int port = 8000;
Private ServerSocket ServerSocket;
Public Echoserver () throws IOException {
ServerSocket = new ServerSocket (port);
System.out.println ("Server Start");
}
public string Echo (String msg) {
return "echo:" + msg;
}
Private PrintWriter getwriter (socket socket) throws IOException {
OutputStream socketout = SOCKET.GETOUTPU Tstream ();
return new PrintWriter (Socketout, true);
}
Private BufferedReader getreader (socket socket) throws IOException {
InputStream socketin = Socke T.getinputstream ();
return new BufferedReader (new InputStreamReader (Socketin));
}
public void service () {
while (true) {
Socket socket = NULL;
try {
socket = serversocket.accept ()//Waiting for client to connect
System.out.println ("New Connection accepted"
+ socket.getinetaddress () + ":" + SoCket.getport ());
BufferedReader br = getreader (socket);
PrintWriter pw = getwriter (socket);
String msg = null;
while (msg = Br.readline ())!= null) {
System.out.println (msg);
Pw.println (Echo (msg));
if (msg.equals ("Bye"))//If the customer sends a message of "Bye", ends the communication
break;
} catch (IOException e) {
E.printstacktrace ();
Finally {
try {
if (socket!= null)
Socket.close ();//Disconnect
} catch (IOException e) {
E.printstacktrace ();
}
}
}
}
public static void Main (String args[]) throws IOException {
N EW Echoserver () service ();
}
}