Java利用socket实现客户端和服务器相互通信

前言:

上一篇讲解了客户端给服务器发送消息,这一篇讲解客户端和服务器相互发送消息,客户端发送消息给服务器,服务器收到客户端的请求然后返回信息给客户端。

1.服务器代码:

**
 * @author: njb
 * @Date: 2020/11/28 18:49
 * @desc: 服务器socket
 */
public class ServerSocket {
​
    //客户端发送信息
    public static void main(String[] args) {
        OutputStream out = null;
        Socket socket = null;
        try {
            //绑定到本地端口
            socket = new Socket("127.0.0.1", 8090);
            //发送消息
            while (true) {
                System.out.println("==========");
                out = socket.getOutputStream();
                //输入文字,从控制台输入
                Scanner san = new Scanner(System.in);
                String str = san.next();
                System.out.println("我:" + str);
                out.write(str.getBytes());
                out.flush();
                //接收信息
                InputStream in = socket.getInputStream();
                //获取输入流里面数据并存储数据
                byte[] b = new byte[1024];
                StringBuffer sb = new StringBuffer();
                String s;
                if (in.read(b) != -1) {
                    s = new String(b);
                    System.out.println(s);
                    sb.append(s);
                }
                System.out.println("来自服务器的数据:" + sb);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.客户端代码:

/**
 * @author: njb
 * @Date: 2020/11/28 18:49
 * @desc: 客户端socket
 */
public class ClientSocket {
    public static void main(String[] args) {
        ServerSocket server;
        try {
            server = new ServerSocket(8090);
            Socket socket=server.accept();
            while(true){
                System.out.println("----------");
                InputStream in;
                try {
                    in = socket.getInputStream();
                    byte [] b=new byte[1024];
                    StringBuffer sb=new StringBuffer();
                    String s;
                    if(in.read(b) !=-1){
                        s=new String(b);
                        sb.append(s);
                    }
                    OutputStream out=socket.getOutputStream();
                    System.out.println("客户端信息:"+sb);
                    Scanner sc=new Scanner(System.in);
                    String str=sc.next();
                    System.out.println("我:"+str);
                    out.write(str.getBytes());
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.启动服务器,客户端发送消息给服务器。

img

4.服务器收到客户端的请求并且发送消息给客户端。

img

5.更多的收发消息:

img

img

6.以上就是服务器和客户端相互发送消息的简单实现,后面会写一篇利用websocket实现简单的聊天和通信.

Java中可以通过Socket实现客户端服务器端之间的网络通信。下面是一个简单的例子: 服务器端: ```java import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8888); } catch (IOException e) { System.err.println("Could not listen on port: 8888."); System.exit(1); } Socket clientSocket = null; try { System.out.println("Waiting for connection..."); clientSocket = serverSocket.accept(); System.out.println("Connection established with: " + clientSocket.getInetAddress().getHostAddress()); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received message: " + inputLine); outputLine = "Server received message: " + inputLine; out.println(outputLine); if (outputLine.equals("bye")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } } ``` 客户端: ```java import java.net.*; import java.io.*; public class Client { public static void main(String[] args) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("localhost", 8888); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Unknown host: localhost."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: localhost."); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); String serverResponse = in.readLine(); System.out.println("Server response: " + serverResponse); if (serverResponse.equals("bye")) break; } out.close(); in.close(); stdIn.close(); socket.close(); } } ``` 以上代码实现了一个简单的客户端服务器端的通信,可以通过命令行输入消息进行交互。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值