首页 > 代码库 > Socket

Socket

1.

 1 ServerSocket ss = new ServerSocket(port);  2   while(true){ //如果有客户端的连接请求,将执行下面的操作  3   Socket client = ss.accept(); //新建客户端对象  4   Handle handle = new Handle(client);//启动个客户端线程,并且一直监听,直到退出,若有多个客户端请求,则会新建多个客户端线程,由此实现多线程  5   }  6  7  8 public class Handle implements Runnable{  9 Socket socket; 10 public Handle(Socket socket){ 11 this.socket = socket; 12 new Thread(this).start();   13 } 14 public void run(){ 15 try{ 16   BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 17             writer.write("返回服务器处理的消息给客户端"); 18             writer.flush(); 19             writer.close();//关闭这个socket 20 21          } catch (Exception e){ 22 } 23 }

2

为了方便用户使用Socket进行通信,Java把Socket封装成了类。如果查看Socket类的源码,代码是比较长的。我们这里创建了一个Socket_来表示下它。

 

 1 public class Socket_ { 2  3     public Socket_() { 4     } 5  6     public Socket_(Proxy proxy) { 7     } 8  9     public Socket_(SocketImpl impl) {10     }11 12     public Socket_(String host, int port) {13     }14 15     public Socket_(InetAddress addr, int port) {16     }17 18     public Socket_(String host, int port, InetAddress localAddr, int localPort) {19     }20 21     public Socket_(InetAddress addr, int port, InetAddress localAddr,22             int localPort) {23     }24 25     public InputStream getInputStream() {26         return null;27     }28 29     public OutputStream getOutputStream() {30         return null;31     }32 33 }

 这样我们可以对Socket类有了大致的了解,对于一般用户只要知道这个套接字能够连接到另一台计算机,并能够获取数据输入输出流着就足够了。

 

 1 import java.io.IOException; 2 import java.io.InputStream; 3 import java.net.Socket; 4 import java.net.UnknownHostException; 5  6 public class TestSocket { 7  8     public static final int BUF_SIZE = 1024; 9 10     public static void main(String[] args) {11         try {12             Socket socket = new Socket("localhost", 5000);13             InputStream input = socket.getInputStream();14 15             // 好了,接下来就是InputStream对象的事了16             // 就像以前介绍的那样,我们将获得大量的数据流17             // 哈哈,准备接收数据吧18             // 这次我们考虑InputStream流的read(byte[] b)方法19 20             byte[] buf = new byte[BUF_SIZE];21             int readCount = 0;22             while ((readCount = input.read(buf)) != 0) {23                 //处理数据buf24             }25 26         } catch (UnknownHostException e) {27             e.printStackTrace();28         } catch (IOException e) {29             e.printStackTrace();30         }31 32     }33 34 }

 

Socket