package Tcp;
import java.io.OutputStream;
import java.net.*;
public class ServerTest2 {
public static void main(String[] args) throws Exception {
new TCPserver().listen();
}
}
class TCPserver{
public void listen()throws Exception{
ServerSocket serverSocket = new ServerSocket(8002);
Socket client = serverSocket.accept();
OutputStream os = client.getOutputStream();
os.write((“Hello Worls”).getBytes());
Thread.sleep(5000);
System.out.println(“交互结束”);
os.close();
client.close();
}
}
package Tcp;
import java.io.InputStream;
import java.net.*;
public class ClientTest {
public static void main(String[] args) throws Exception {
new TCPclient().connect();
}
}
class TCPclient{
private static final int PORT = 8002;
public void connect()throws Exception{
Socket client = new Socket(InetAddress.getLocalHost(),PORT);
InputStream is = client.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
System.out.println(new String(buf,0,len));
client.close();
}
} 使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。
最新推荐文章于 2022-04-28 12:26:59 发布
本文提供了一个简单的 Java TCP 服务器与客户端的实现案例。服务器监听 8002 端口,并向连接的客户端发送消息;客户端连接到该端口并接收服务器发来的消息。此示例适用于初学者理解 TCP 通信的基本原理。

1604

被折叠的 条评论
为什么被折叠?



