Get the App
SLTechnology News&Howtos  ›  Network Security  › 

ServerSocket and Socket

Shulou Source: shulou.com Published: 2022-06-01 06:25:48 10月04日 Update

Preface

Use ServerSocket and Socket to make a demo for Server and Client communication, and learn to use several commonly used classes under the java.net and java.io packages in this demo process.

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 for socket request System.out.println on client port 5000 ("server startup") } catch (IOException e) {e.printStackTrace ();}} public void start () {Socket socket=null; while (true) {try {socket=serversocket.accept (); / / accept 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 to the client bw.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 commonly used classes in the java.net package:

ServerSocket 、

Socket 、

OutputStream 、 InputStream 、

InputStreamReader 、 OutputStreamWriter 、

BufferedReader 、 BufferedWriter 、

InetAddress 、

Tags: Client client commonly used server service communication usage preface message port process learning testing monitoring Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Information Shulou Tech Info NVidia Redmi