Socket,开发那些事

TCP/IP通信协议是一种可靠的网络协议,它在通信的两端各建立一个Socket,从而在通信的两端之间形成网络虚拟链路。
一旦建立了虚拟网络链路,两端的程序就可以通过虚拟链路进行通信。Java对于TCP协议的网络通信提供了良好的封装,
Java使用Socket对象来达标两端的通信端口,并通过Socket产生IO流来进行网络通信。

ServerSocket

Socket accept():如果接收到一个客户端Socket的连接请求,该方法将返回一个与客户端Socket对应的Socket;否则该
方法将一直处于等待状态。
ServerSocket(int port):用来指定的端口port(0~65535)来创建一个ServerSocket。

//创建一个ServerSocket,用于监听客户端的Socket的连接请求
ServerSocket mServerSocket= new ServerSocket(3000);
//采用循环不断地接收来自客户端的请求
while (true){
//每当接收到客户端Socket的请求时,服务端也对应产生一个Socket
Socket mSocket=mServerSocket.accept();
}

Socket

Socket(InetAddress/Sting remoteAddress,int port):创建连接到指定远程主机、远程端口的Socket

//创建连接到本机、3000端口的Socket
Socket mSocket= new Socket("127.0.0.1",3000);

IO流

InputStream getInputStream():返回该Socket对象对应的输入流,让程序通过该输入流从Socket中取出数据
OutputStream getOutputStream():返回该Socket对象对应的输出流,让程序通过该输入流从Socket中取出数据

服务端:

//创建一个ServerSocket,用于监听客户端的Socket的连接请求
ServerSocket mServerSocket= new ServerSocket(3000);
while(true){
//每当结束到客户端Socket的请求时,服务端也对应产生一个Soket
Socket mSocket=mServerSocket.accept();
//将Socket对饮的输出流包装成PrintStream
PrintStream ps=new PrintStream(mSocket.getInputStream());
ps.println("this is testing!");
ps.close();
mSocket.close();
}

客户端:

Socket mSocket=new Socket("127.0.0.1" ,3000);
BufferedReader br = new BufferedReader(new InputStreamReader(mSocket.getInputStream());
//进行普通IO操作
String line = br.readLine();
System.out.println("来自服务端的数据:"+line);
br.close();
mSocket.close();

SocketClient&SocketServer

将socket客户端封装成SocketClient类,并提供connect(ip,port)、send()方法,通过接口类SocketListener来回掉onReceive( msg)、onSend()接收发送的信息。关键代码如下:

  /**
    * 连接服务端
    * @param serverIp
    * @param serverPort
    */


   public void connect(final String serverIp, final int serverPort) {

       // 开启一个线程启动tcp socket
       new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   byte[] buffer;
                   String msg;
                   mSocket = new Socket(serverIp, serverPort);
                   InputStream inStream = mSocket.getInputStream();
                   in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                   out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                           mSocket.getOutputStream())), true);
                   while (true) {
                       buffer = new byte[512];
                       if (mSocket.isConnected()) {
                           if (!mSocket.isInputShutdown()) {
//                                if ((content = in.readLine()) != null) {
//                                    content += "\n";
//                                    if (mSocketListener != null)
//                                        mSocketListener.onReceive(content);
//                                }

                               if (inStream.read(buffer) != 0) {
                                   msg = new String(buffer, "UTF-8").trim();
                                   if (mSocketListener != null)
                                       mSocketListener.onReceive(msg);

                               }


                           }
                       }

                   }
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }).start();
   }
   

将socket服务端封装成SocketServer类,并提供startServerSocket(serverPort),通过接口类SocketListener来回掉onReceive( msg)、onSend()接收发送的信息。关键代码如下:

public void startServerSocket(final int serverPort) {

       new Thread(new Runnable() {
           @Override
           public void run() {
               // TODO Auto-generated method stub
               try {
                   mServerSocket = new ServerSocket(serverPort);
                   mExecutorService = Executors.newCachedThreadPool();
                   while (true) {
                       socket = mServerSocket.accept();
                       mExecutorService.execute(new ReceiveThread(socket));
                       System.out.println("----connected success----");
                   }

               } catch (UnknownHostException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   System.out.println("UnknownHostException-->" + e.toString());
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   System.out.println("IOException" + e.toString());
               }
           }
       }).start();
   }
Socket,开发那些事_第1张图片
SocketClient.png

Demo地址

感谢以下文章提供的帮助:
Socket,你需要知道的事儿

你可能感兴趣的:(Socket,开发那些事)