网络通信协议(Network Communicaton Protocol)
TCP协议(Transmission Control Protocol)
- 使用TCP协议前,必须先建立TCP连接,形成传输数据通道。
- 传输前,采用“三次握手”方式,点对点通信,是可靠的。
- TCP协议进行通信的两个应用进程:客户端、服务端。
- 在连接中可进行大量数据传输。
- 传输完毕,需要释放已建立的连接,效率低。
Java实现TCP通信
tcp客户端
public class TcpClient {
public static void main(String[] args) {
TcpClient tcpClient = new TcpClient();
tcpClient.tcpClient();
}
public void tcpClient(){
Socket socket = null;
OutputStream os = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,10098);
os = socket.getOutputStream();
os.write("在吗".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
tcp服务端
public class TcpServer {
public static void main(String[] args) {
TcpServer tcpServer = new TcpServer();
tcpServer.tcpServer();
}
public void tcpServer(){
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
InputStreamReader isr = null;
try {
serverSocket = new ServerSocket(10098);
socket = serverSocket.accept();
is = socket.getInputStream();
isr = new InputStreamReader(is);
char[] chars = new char[1024];
int len;
while ((len = isr.read(chars,0,chars.length))!=-1){
System.out.println(new String(chars,0,len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(serverSocket != null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
UDP协议(User Datagram Protocol)
- 将数据、源、目的封装成数据包,不需要建立连接。
- 每个数据包的大小限制在64k内。
- 发送方不管对方是否准备好,接收方也不确认,是不可靠的。
- 可以广播发送。
- 发送数据结束时,无需释放资源,开销小,速度快。
udp发送方
public class UdpSender {
public static void main(String[] args) throws IOException {
UdpSender udpSender = new UdpSender();
udpSender.sender();
}
public void sender() throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
String str = "你好";
InetAddress inet = InetAddress.getByName("127.0.0.1");
byte[] data = str.getBytes();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
datagramSocket.send(packet);
datagramSocket.close();
}
}
udp接收方
public class UdpReceiver {
public static void main(String[] args) throws IOException {
UdpReceiver udpReceiver = new UdpReceiver();
udpReceiver.receiver();
}
public void receiver() throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(9090);
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data,0,data.length);
datagramSocket.receive(packet);
System.out.println(new String(data,0,packet.getLength()));
datagramSocket.close();
}
}