Socket网络编程

Posted cppdy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Socket网络编程相关的知识,希望对你有一定的参考价值。

TCP协议网络通讯案例(http协议)

1、创建TcpServer(tcp服务端)

package com.cppdy.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

//tcp服务端
public class TcpServer {

    public static void main(String[] args) throws Exception {

        System.out.println("tcp服务端启动啦……");
        ServerSocket serverSocket = new ServerSocket(8080);
        try {
            // 会阻塞在这里,等待连接
            Socket accept = serverSocket.accept();

            InputStream inputStream = accept.getInputStream();

            byte[] bytes = new byte[1024];

            int length = inputStream.read(bytes);

            String result = new String(bytes, 0, length);

            System.out.println("服务端接收到客户端发送的消息:" + result);

            OutputStream outputStream = accept.getOutputStream();

            PrintWriter printWriter = new PrintWriter(outputStream);

            printWriter.println("服务器收到消息了,这是服务器自动反馈……");

            printWriter.flush();

            accept.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }

}

2、创建TcpClient(tcp客户端)

package com.cppdy.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

//tcp客户端
public class TcpClient {

    public static void main(String[] args) throws Exception {

        Socket socket = new Socket("127.0.0.1", 8080);

        try {
            OutputStream outputStream = socket.getOutputStream();

            String msg = "吹泡泡的魚";

            outputStream.write(msg.getBytes());

            System.out.println("客户端发送消息完毕……");

            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

            String result = br.readLine();

            System.out.println("客户端==》服务器返回的结果:" + result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

}

 

以上是关于Socket网络编程的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段——JS中的面向对象编程

VSCode自定义代码片段9——JS中的面向对象编程

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

Python--网络编程-----socket代码实例