TCP通信
客户端:
- 连接服务器socket
- 发送消息
- 关闭资源(判空)
服务端:
- 建立服务端口 serverSocket
- 等待客户端连接 accept
- 接收客户端消息
- 关闭资源(判空)
例:
客户端:
package com.zuoyan.lesson02;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* 客户端
*/
public class ClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
InetAddress serverIP = null;
OutputStream os = null;
try {
serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//建立连接
socket = new Socket(serverIP, port);
//发送消息
os = socket.getOutputStream();
os.write("测试通信消息发送".getBytes());
} catch (Exception 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();
}
}
}
}
}
服务端:
package com.zuoyan.lesson02;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务端
*/
public class ServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
//创建一个地址
try {
serverSocket = new ServerSocket(9999);
while (true) {
//等待客户连接过来
socket = serverSocket.accept();
//读取客户传递信息
is = socket.getInputStream();
//管道流
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
System.out.println(baos.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (baos != null) {
try {
baos.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 (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}