Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

ServerSocket and Socket

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

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 、

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report