Socket 编程

1.什么是Socket

网络通信接口,通常也称作“套接字”,用于描述IP地址和端口,是一个通信链的句柄。

应用程序通常通过“套接字”向网络发出请求或者应答网络请求。

2.Socket基本通信模型

 

3.使用基于TCP协议的Socket

服务器端:

ServerSocket serverSocket = new ServerSocket(4567);

Socket socket = serverSocket.accept();

InputStream is = socket.getInputStream();

 

客户端:

Socket socket = new Socket(“192.168.1.1”, 4567);

OutputStream os = socket.getOutputStream();

byte data[] = …;

os.write(data, 0, data.length);

4.使用基于UDP协议的Socket

服务器端:

DatagramSocket socket = new DatagramSocket(4567);

byte buffer [] = new byte[1024];

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

socket.receive(packet);

 

接收的数据:packet.getData()

数据偏移量:packet.getOffset()

数据长度: packet.getLength()

 

客户端:

DatagramSocket socket = new DatagramSocket (4567);

InetAddress serverAddress = InetAddress.getByName(“192.168.1.1”);

byte data[] = …;

DatagramPacket packet = new DatagramPacket (data, data.length, serverAddress, 4567);

socket.send(packet);

你可能感兴趣的:(socket)