首页 > 代码库 > Java实现简单的socket通信

Java实现简单的socket通信

  今天学习了一下java如何实现socket通信,感觉难点反而是在io上,因为java对socket封装已经很完善了。

  今天代码花了整个晚上调试,主要原因是io的flush问题和命令行下如何运行具有package的类,不过最后问题基本都解决了,把代码贴出来供大家参考

server

public class TcpServer {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(9091);
        try {
            Socket client = server.accept();
            try {
                BufferedReader input =
                        new BufferedReader(new InputStreamReader(client.getInputStream()));
                boolean flag = true;
                int count = 1;
 
                while (flag) {
                    System.out.println(客户端要开始发骚了,这是第 + count + 次!);
                    count++;
                     
                    String line = input.readLine();
                    System.out.println(客户端说: + line);
                     
                    if (line.equals(exit)) {
                        flag = false;
                        System.out.println(客户端不想玩了!);
                    } else {
                        System.out.println(客户端说:  + line);
                    }
 
                }
            } finally {
                client.close();
            }
             
        } finally {
            server.close();
        }
    }
}

client

public class TcpClient {
    public static void main(String[] args) throws Exception {
        Socket client = new Socket(127.0.0.1, 9091);
        try {
            PrintWriter output =
                    new PrintWriter(client.getOutputStream(), true);
            Scanner cin = new Scanner(System.in);
            String words;
 
            while (cin.hasNext()) {
                words = cin.nextLine();
 
                output.println(words);
 
                System.out.println(写出了数据:  + words);
            }
 
            cin.close();
        } finally {
            client.close();
        }
    }
}

 

Java实现简单的socket通信