TCP连接是最常用的网络通信方式之一,其特点是:连接一直存在,随时可以发送和接收数据。一旦连接断开,发送和接收都会失败(抛出异常)。
Server端代码
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketTest {
public static void main(String[] args) throws IOException {
// Server端监听10000端口
ServerSocket serverSocket = new ServerSocket(10000);
// 等待客户端连接,此时进入阻塞状态
Socket socket = serverSocket.accept();
System.out.println("Connected: " + socket.getRemoteSocketAddress());
// 从Socket读取数据
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int length = inputStream.read(b);
System.out.println(length + " Bytes Received");
}
}
客户端代码
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class ClientSocketTest {
public static void main(String[] args) throws IOException {
// 与服务器建立连接
Socket socket = new Socket("127.0.0.1", 10000);
// 发送数据
OutputStream outputStream = socket.getOutputStream();
byte[] b = new byte[2];
outputStream.write(b);
}
}