客户端:
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
public class TcpExample {
public static void main (String[]args)throws Exception{
new TcpC().connect(); //创建TCPClient对象,并调用connect()方法
}
}
class TcpC {
private static final int PORT=8002;
public void connect()throws Exception {
//创建一个Socket并连接到给出地址和端口号的计算机
Socket client =new Socket(InetAddress.getLocalHost(),PORT);
InputStream is=client.getInputStream(); //得到接收数据的流
byte[]buf=new byte[1024]; //定义1024 个字节数组的缓冲区
int len =is.read(buf); //将数据读到缓冲区中
System.out.println(new String (buf,0,len));
client.close();
}
}服务器:import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpExampleS {
public static void main(String[] args) throws Exception {
new TcpServer().listen(); //创建TcpServer对象,并调用listen()方法
}
}
class TcpServer{
private static final int PORT=8002; //定义一个端口号
public void listen()throws Exception{//定义一个listen()方法,抛出一个异常
ServerSocket serverSocket =new ServerSocket(PORT); //创建ServerSocket对象
Socket client=serverSocket.accept();//调用ServerSocket的accept()方法接受数据
OutputStream os=client.getOutputStream();
os.write(("Hello worlld").getBytes());
Thread.sleep(5000);
os.close();
client.close();
}
}运行结果:
本文提供了一个简单的TCP客户端和服务器实现示例。客户端通过指定端口连接到服务器,接收服务器发送的消息“Helloworld”。服务器监听指定端口,等待客户端连接,并向连接的客户端发送消息。
1005

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



