简单的 Socket实例

Socket简介
网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。
建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API),对TCP/IP的封装,TCP/IP也要提供可供程序员做网络开发所用的接口,这就是Socket编程接口;HTTP是轿车,提供了封装或者显示数据的具体形式;Socket是发动机,提供了网络通信的能力。

Socket的英文原义是“孔”或“插座”。作为BSD UNIX的进程通信机制,取后一种意思。通常也称作”套接字“,用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。Socket正如其英文原义那样,像一个多孔插座。一台主机犹如布满各种插座的房间,每个插座有一个编号,有的插座提供220伏交流电, 有的提供110伏交流电,有的则提供有线电视节目。 客户软件将插头插到不同编号的插座,就可以得到不同的服务。

用Java实现Socket通信很方便,功能也很齐全,下面举个简单的例子:
Socket通信的实现需要一个服务端一个客户端

package com.nms.common;

import java.io.OutputStream;
import java.net.Socket;

public class socketClient {
    public static void main(String args[]) throws Exception {
        // 要连接的服务端IP地址和端口
        String host = "127.0.0.1"; 
        int port = 55533;
        // 与服务端建立连接
        Socket socket = new Socket(host,port);
        // 建立连接后获得输出流
        OutputStream outputStream = socket.getOutputStream();
        String message="你好 哈哈哈";
        socket.getOutputStream().write(message.getBytes("UTF-8"));
        outputStream.close();
        socket.close();
      }
}
package com.nms.common;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class socketSever {
    public static void main(String[] args) throws Exception {
        // 监听指定的端口
        int port = 6666;
        ServerSocket server = new ServerSocket(port);  
        // server将一直等待连接的到来
        System.out.println("server将一直等待连接的到来");
        Socket socket = server.accept();
        // 建立好连接后,从socket中获取输入流,并建立缓冲区进行读取
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder stringBuilder = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
          //注意指定编码格式,发送方和接收方一定要统一,建议使用UTF-8
         stringBuilder.append(new String(bytes, 0, len,"UTF-8"));
        }
        System.out.println("收到client的消息了: " + stringBuilder);
        inputStream.close();
        socket.close();
        server.close();
      }
}

一般用到socket都是要进行全双工的通信的,也就是双方都既能收又能发,类似qq的聊天一样,那么服务端就要考虑采用多线程处理发过来的多个连接,可以考虑使用线程池,客户端类似。
自定义线程类:

package com.nms.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class MyThread implements Runnable{
    private Socket socket;
    @Override
    public void run () {
        // TODO Auto-generated method stub
         // 建立好连接后,从socket中获取输入流,并建立缓冲区进行读取
      InputStream inputStream;
        try {
        inputStream = this.socket.getInputStream();
      byte[] bytes = new byte[1024];
      int len;
      StringBuilder stringBuilder = new StringBuilder();
      while ((len = inputStream.read(bytes)) != -1) {
        // 注意指定编码格式,发送方和接收方一定要统一,建议使用UTF-8
        stringBuilder.append(new String(bytes, 0, len, "UTF-8"));
      }
      System.out.println("收到来自client的消息: " + stringBuilder);
      inputStream.close();
      socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public Socket getSocket () {
        return socket;
    }
    public void setSocket (Socket socket) {
        this.socket = socket;
    }

}

多线程处理的服务端:这里实现了一个操作是先接受发来的数据长度再接收数据,从而让客户端可以一直发送消息而不是发送一次就关闭连接和流

package com.nms.utils;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class socketSever2 {
    public static void setUpSocket() throws Exception {
         // 监听指定的端口
        int port = 8001;
        ServerSocket server = new ServerSocket(port);
        // server将一直等待连接的到来
        System.out.println("server将一直等待连接的到来");
        //如果使用多线程,那就需要线程池,防止并发过高时创建过多线程耗尽资源
        ExecutorService threadPool = Executors.newFixedThreadPool(100);     
        while (true) {
          Socket socket = server.accept();
          MyThread runnable = new MyThread();
          runnable.setSocket(socket);
          threadPool.execute(runnable);
      }
    }
}

客户端实现循环发送数据

package com.nms.utils;

import java.io.OutputStream;
import java.net.Socket;

public class socketClient {
    private static Socket socket;
    public static void setUpSocket() throws Exception {
         // 要连接的服务端IP地址和端口
        String host = "127.0.0.1";
        int port = 8000;
        // 与服务端建立连接
        socket = new Socket(host, port);
        // 建立连接后获得输出流
        OutputStream outputStream = socket.getOutputStream();
        String message = "你好  哈哈哈";
        //首先需要计算得知消息的长度
        byte[] sendBytes = message.getBytes("UTF-8");              
        for(int i=0;i<10;i++){
         message = "第"+i+"个 message!";
            sendBytes = message.getBytes("UTF-8");
            //然后将消息的长度优先发送出去
            outputStream.write(sendBytes.length >>8);
            //然后将消息再次发送出去
            outputStream.write(sendBytes.length);
            outputStream.write(sendBytes);  
            outputStream.flush();
        }
        System.out.println("数据发送完毕!");
        outputStream.close();

      }
    public static void colseSocket() throws Exception {
        socket.close();
    }
}

猜你喜欢

转载自blog.csdn.net/Phoenix_smf/article/details/80135832