TCP之JAVA通信

服务器端

public class TCPServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        while (true) {
            try {
                serverSocket = new ServerSocket(9999);
                socket = serverSocket.accept();
                is = socket.getInputStream();

                bos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                System.out.println(bos.toString());


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }
        }
    }
}

客户端

public class TCPCilent {

    public static void main(String[] args) {
        Socket socket =null;
        OutputStream os=null;

        try {
            InetAddress serverIP=InetAddress.getByName("127.0.0.1");
            int port=9999;
            socket = new Socket(serverIP, port);
            os = socket.getOutputStream();
            os.write("hello".getBytes())  
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
上一篇:I/O(二)—— NIO


下一篇:批量图片处理:如何给多个图片都加上连续的序号?