网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。(百度百科)
对于socket,无非就是建立一个双向的网络通信链路。socket是对TCP/IP进行了封装的一个类。socket出现只是为了方便程序员处理基于tcp/ip协议的网络通信的处理。
首先我们要建立一个socket服务端。上代码:
ServerSocket server = null;
ExecutorService executor = Executors.newCachedThreadPool();
try {
// new a socket server
server = new ServerSocket(39998);
// start to listen, this step will be blocked
Socket request = server.accept();
// when getting a request, server will start a thread to handle the request.
// and then keep going to listen.
executor.execute(new HandleDataThread(request, counter));
server.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
至此为止,我们建立了一个socket的服务端,启动该服务端等待客户端的连接。
客户端通过建立一个socket连接至目标地址,而服务端通过暴露给客户端的接口,供客户端连接。上代码:
try {
socket.connect(new InetSocketAddress("127.0.0.1", 39998));
if(socket.isConnected()){
outputStream = socket.getOutputStream();
outputStream.write(msg);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
close();
}
至此,我们的一个简单的socket通信交互就完成了。当然,socket通信还包括短链接,长连接等,长连接无非是启动一个心跳线程并发进行,保证连接持续可用。
值得注意的是:
socket数据传输时以字节流的形式传输的,我们时常会遇见字节流拼接的问题,字节数组的拼接:
byte[] bMsgBody = msgBody.getBytes();
int bodyLength = bMsgBody.length;
byte[] bHead = new DecimalFormat("000000").format(bodyLength).getBytes();
byte[] msg = new byte[bHead.length+bMsgBody.length];
System.arraycopy(bHead, 0, msg, 0, bHead.length);
System.arraycopy(bMsgBody, 0, msg, bHead.length, bMsgBody.length);