编程语言
首页 > 编程语言> > java socket

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,printStackTrace,IOException,catch,new,null
来源: https://www.cnblogs.com/cciscc/p/16214709.html