s-day11-TCP服务器端代码的实现

This commit is contained in:
2026-08-14 10:30:54 +08:00
parent bd8e266e3e
commit 6dfd47714d
2 changed files with 56 additions and 0 deletions
@@ -39,6 +39,7 @@ public class TcpClientDemo06 {
//一次读取一个字节数组 //一次读取一个字节数组
byte[] bytes = new byte[1024]; byte[] bytes = new byte[1024];
int len; int len;
System.out.println("服务器响应的数据为:");
while ((len = is.read(bytes)) != -1) { while ((len = is.read(bytes)) != -1) {
System.out.println(new String(bytes,0,len)); System.out.println(new String(bytes,0,len));
} }
@@ -0,0 +1,55 @@
package com.inmind.tcp03;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
TCP服务器端代码的实现
在java中使用类ServerSocket表示服务器
构造方法:
ServerSocket(int port) 创建绑定到指定端口的服务器套接字。
参数port:服务器软件的端口号
常用方法:
Socket accept() 接收客户端的请求,还将客户端的请求数据封装到服务器的Socket对象返回值中
InetAddress getInetAddress() 返回套接字所连接的地址。
InputStream getInputStream() 返回此套接字的输入流.(接收请求数据的)
OutputStream getOutputStream() 返回此套接字的输出流。 (发送响应数据)
void close() 关闭此套接字。
服务器的实现步骤:
1.创建服务器对象
2.接收客户端请求
3.获取请求数据
4.业务逻辑代码
5.发送响应数据
6.释放资源
*/
public class TcpServerDemo07 {
public static void main(String[] args) throws Exception {
//1.创建服务器对象
ServerSocket serverSocket = new ServerSocket(10024);
//2.接收客户端请求
Socket socket = serverSocket.accept();//阻塞的方法,等待客户端发来请求
System.out.println(socket.getInetAddress());//获取客户端的ip地址
//3.获取请求数据
InputStream is = socket.getInputStream();
//一次读取一个字节数组
byte[] bytes = new byte[1024];
int len;
System.out.println("客户端请求数据为:");
while ((len = is.read(bytes)) != -1) {
System.out.println(new String(bytes,0,len));//请求数据的展示
}
//4.业务逻辑代码
String result = "www.taobao.com";//要响应的数据
//5.发送响应数据
OutputStream os = socket.getOutputStream();
os.write(result.getBytes());
//6.释放资源
socket.close();
serverSocket.close();
}
}