javaSE--网络编程入门

socket套接字:相当于客户端服务端之间的管道

服务端:

public class QQServer {
    public static void main(String[] args) throws Exception{
//        创建服务器
        ServerSocket server = new ServerSocket();
//      服务器绑定端口
        server.bind(new InetSocketAddress(8888));
//         服务器傻等消息
        System.out.println("服务器启动!");
        Socket accept =server.accept();

//        若有消息来了,就用流接收
        InputStream in = accept.getInputStream();
        int len;
        byte[] buffer =new byte[1024];

        while ((len=in.read(buffer))!=-1){
            System.out.println(new String(buffer,0,len));
        }

        in.close();
    }
}

客户端:

public class QQClient {
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress("127.0.0.1",8888));

        OutputStream out = socket.getOutputStream();
        String msg="slee";

        out.write(msg.getBytes()); //getBytes();
        out.flush();
        out.close();
    }
}

你可能感兴趣的:(java基础)