java socket

2022/5/2 1:12:41

本文主要是介绍java socket,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.客户端传输到服务端

 

public void service() {
    ServerSocket serverSocket = null;
    InputStreamReader inputStreamReader = null;
    try {
        serverSocket = new ServerSocket(8899);
        Socket accept = serverSocket.accept();
        InputStream inputStream = accept.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream);
        char[] cbuf = new char[5];
        int len = 0;
        while ( (len = inputStreamReader.read(cbuf))!=-1 ){
            System.out.print(new String(cbuf, 0, len));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
@Test
public void client() {
    Socket socket = null;
    OutputStreamWriter outputStreamWriter = null;
    try {
        InetAddress localHost = InetAddress.getLocalHost();
        socket = new Socket(localHost,8899);
        OutputStream outputStream = socket.getOutputStream();
        outputStreamWriter = new OutputStreamWriter(outputStream);
        outputStreamWriter.write("你好,我是客户端");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStreamWriter != null) {
            try {
                outputStreamWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 



这篇关于java socket的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程