tcp/ip协议–网络编程的Java代码
//创建服务端的Socket对象
ServerSocket serverSocket = new ServerSocket();
//服务端绑定端口
serverSocket.bind(new InetSocketAddress(8899));
//监听客户端的连接(阻塞的方法),返回的是当前连接到服务器的客户端的对象
Socket socket = serverSocket.accept();
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
//读数据
byte[] buf = new byte[2];
int len;
//调用read方法返回阻塞,当没有数据时会阻塞,并不会返回-1
while ((len = inputStream.read(buf)) != -1) {
String str = new String(buf, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
//创建Socket的客户端的对象
Socket socket = new Socket();
//连接服务器,当然客户端也可以绑定端口,如果不绑定端口,则每次随机分配一个没有使用的端口
socket.connect(new InetSocketAddress("127.0.0.1", 8899));
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello".getBytes());
outputStream.flush();
outputStream.close();
socket.close();
socket | 所用的类名,方法名 |
---|
服务器端 | ServerSocket |
客户端 | socket |