ServerSocket and Socket, serversocketsocket
Preface
A Server and Client communication demo is provided with ServerSocket and Socket, and several common classes under java.net and java. io packages are used in this demo.
Server
Import java.net. *; import java. io. *; public class HttpServer {public static void main (String [] args) {new HttpServer (). start () ;}private ServerSocket serversocket = null; public HttpServer () {try {serversocket = new ServerSocket (5000); // listen to the socket request System on the client port 5000. out. println ("server startup");} catch (IOException e) {e. printStackTrace () ;}} public void start () {Socket socket = null; while (true) {try {socket = serve Rsocket. accept (); // accept the client request socket System. out. println ("address:" + socket. getInetAddress () + ":" + socket. getLocalPort (); OutputStream OS = socket. getOutputStream (); BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (OS); // send a message bw to the client. write ("test server communication \ n"); bw. flush ();} catch (IOException e) {e. printStackTrace (); System. out. println ("disconnected");} finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e ){}}}}}
Client
import java.net.*;import java.io.*;public class Client{ public static void main(String[] args){ Socket socket=null; try{ socket =new Socket("127.0.0.1",5000); InputStream is =socket.getInputStream(); InputStreamReader isr=new InputStreamReader(is); BufferedReader br =new BufferedReader (isr); String mess=br.readLine(); System.out.println("mess:"+mess); }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(socket !=null){ socket.close(); } }catch(IOException e){ } } } }
Summary
Several common classes in the java.net package:
ServerSocket,
Socket,
OutputStream, InputStream,
InputStreamReader, OutputStreamWriter,
BufferedReader, BufferedWriter,
InetAddress,