Socket Simple Demo

There Socket protocol-line presentation of a lot, not in the superfluous, the paper to write a small Demo, which was introduced to the specific implementation

A: Socket server

 

 

package com.founderit;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloServer {

public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
ServerSocket serverSocket= new ServerSocket(1234);
while (true){
Socket socket= serverSocket.accept();
in=socket.getInputStream();
InputStreamReader reader= new InputStreamReader(in);
StringBuilder builder=new StringBuilder();
for (int c = reader.read(); c != -1; c = reader.read()) {
builder.append ((char) C);
}
System.out.println ( "client request is received: -------" + builder.toString ());
OUT = Socket.getOutputStream ();
out.write ( "request has been received, over" .getBytes ());
out.flush ();
socket.shutdownOutput ();
}
} the catch (IOException E) {
e.printStackTrace ();
} {the finally
the try {
in. Close ();
the out.close ();
} the catch (Exception E) {
e.printStackTrace ();
}
}
}
}

two: Socket client

 

 

 

 

com.founderit.controller Package; 

Import the java.io. *;
Import the java.net.Socket;

public class the SocketClient {
public static void main (String [] args) {
the OutputStream OUT = null;
the InputStream in = null;
the Socket Socket = null ;
the try {
Socket new new = the Socket ( "localhost", 1234);
OUT = Socket.getOutputStream ();
out.write ( "call server, receive the answer" .getBytes ());
socket.shutdownOutput ();
// takes an input stream and reads the server response information
in Socket.getInputStream = ();
the BufferedReader the BufferedReader br = new new (new new the InputStreamReader (in));
the StringBuilder the StringBuilder new new SB = ();
Info = null String;
the while ((info = br.readLine ()) = null!) {
Sb.append (info);
}
System.out.println ( "server receives reply:" + sb.toString ()) ;
br.close ();
} the catch (IOException E) {
e.printStackTrace ();
} {the finally
the try {
out.flush ();
the out.close ();
in.close ();
the Socket.close ();
} the catch (Exception E) {
e.printStackTrace ();
}
}
}

}

is first performed Socket server, it would have been waiting to receive a request to run, create a need to bind socketServer port, the port needs to be consistent with the need client
Socket client is then performed, it sends a request to the server Socket server and receives feedback, the following operation effect

 

 

 

 

 Note that both the client and server, after the implementation of write () method to perform the best socket.shutdownOutput () method to close the output stream, or has a chance to write unsuccessful (reason unknown)

 





Guess you like

Origin www.cnblogs.com/lovetq520/p/11671187.html