tcp实现聊天

客户端

复制代码
 1 public class A {
 2     public static void main(String[] args) throws IOException {
 3         String guo="你好啊";
 4        int port=8888;
 5         Socket socket = null;
 6         InetAddress ip = InetAddress.getByName("127.0.0.1");
 7         socket=new Socket(ip,port);
 8         OutputStream outputStream = socket.getOutputStream();
 9         outputStream.write(guo.getBytes());
10         socket.close();
11         outputStream.flush();
12         outputStream.close();
13 
14     }
15 }
复制代码

服务器端

复制代码
public class B {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            byteArrayOutputStream.write(bytes,0,len);
    }
        System.out.println(byteArrayOutputStream.toString());
        socket.close();
        inputStream.close();
        byteArrayOutputStream.flush();
        byteArrayOutputStream.close();
    }
}
复制代码

 

posted on   大风吹过12138  阅读(13)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示