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

Java Socket 编程实验总结

时间:2015-05-03 01:55:43      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

Client:

1.使用Socket类  

if (socket == null)
socket = new Socket(address, 2333);
//不要用1024之前的端口

2.socket通过对其中的outputstream和inputstream操作实现通讯

  if (writer == null)
        writer = new PrintWriter(socket.getOutputStream());
  writer.println(toSend);
  writer.flush();//一定要记得flush刷新
 
 BufferedReader reader = new BufferedReader(new     InputStreamReader(socket.getInputStream()));
                    while(!socket.isClosed()) {
                        sleep(100);
                        String line = reader.readLine();
                        if(line!=null){
                            textArea.append(line + "\n");
                        }
                    }
                    reader.close();    

3.修改JFrame默认关闭窗口事件

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                System.exit(0);
            }

        });

 

Server:

1.使用ServerSocket

  serverSocket = new ServerSocket(2333);

2.广播实现

  socketList = new ArrayList<Socket>();
        try {

            serverSocket = new ServerSocket(2333);
            while (true) {
                Socket socket = serverSocket.accept();
                if(!socketList.contains(socket)){
                    socketList.add(socket);
                    new SocketThread(socket);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

3.使用多线程

 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (socket.isClosed() == false) {
                    sleep(100);
                    String line = reader.readLine();
                    if (line != null) {
                        for (int i = 0; i < socketList.size(); i++) {
                            Socket iter = (Socket) socketList.get(i);
                            PrintWriter writer = new PrintWriter(iter.getOutputStream());
                            System.out.println(line);
                            writer.println(line);
                            writer.flush();
                        }
                    }
                }
                socketList.remove(socket);

 

 

在室友电脑上初次运行客户端时无法访问到我的服务器,把我的Server打成jar包后运行把防火墙取消后成功完成了通讯!

Java Socket 编程实验总结

标签:

原文地址:http://www.cnblogs.com/Run-dream/p/4472810.html

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