码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现简单的socket通信

时间:2017-02-07 19:02:06      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:throw   output   equal   static   print   buffer   rds   while   exception   

  今天学习了一下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通信

标签:throw   output   equal   static   print   buffer   rds   while   exception   

原文地址:http://www.cnblogs.com/liushao/p/6375446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!