zoukankan      html  css  js  c++  java
  • 简单的控制台聊天(TCP)


    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.util.Scanner;

    //TCP通信客户端
    public class TCPClient {

    public static Scanner scanner=new Scanner(System.in);
    public static void main(String[] args) throws IOException {
    Socket socket=new Socket("127.0.0.1",8888);
    System.out.println("到达客户端。。。");
    OutputStream os = socket.getOutputStream();
    os.write("服务器是你吗?".getBytes());

    while (true){
    InputStream is = socket.getInputStream();
    byte[] bytes =new byte[1024];
    int len = is.read(bytes);
    System.out.println("服务器:"+new String(bytes,0,len));
    String cilent = scanner.nextLine();
    os.write(cilent.getBytes());

    //关闭流,释放资源
    // os.close();
    }
    }
    }









    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;

    //TCP通信服务端
    public class TCPServer {
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(8888);
    Socket socket = server.accept();
    System.out.println("启动服务。。。");
    while (true){
    InputStream is = socket.getInputStream();
    byte[] bytes = new byte[1024];
    int len = is.read(bytes);
    System.out.println("客户端: "+new String(bytes, 0, len));
    OutputStream os = socket.getOutputStream();
    // os.write("我是服务器".getBytes());
    String servers = scanner.nextLine();
    os.write(servers.getBytes());
    // os.close();
    // server.close();
    }
    }
    }












  • 相关阅读:
    windows下配置mysql环境变量
    360Top奢侈品演示站
    CSS3性能体验
    使用jquery获取radio的值
    获取select 的 val 和 text [转引]
    PHP时间比较和时间差如何计算
    InnoDB和MyISAM的区别与选择
    大型网站技术架构学习摘要
    大型网站系统架构分析--转
    一步步构建大型网站架构-转
  • 原文地址:https://www.cnblogs.com/LQ970811/p/12713180.html
Copyright © 2011-2022 走看看