服务器端,要先开启
import java.io.*;
import java.net.*;
public class Example004 {
public static void main(String[] args) throws Exception {
// TODO 自动生成的方法存根
new TCPServer().listen();
}
}
//TCP服务端,单线程
class TCPServer{
private static final int PORT=7765;
public void listen () throws Exception{
ServerSocket serverSocket = new ServerSocket(PORT);//绑定指定的端口
Socket client = serverSocket.accept();//接收来自客户端的请求,返回一个监听套接字
OutputStream os = client.getOutputStream();//向客户端发送消息,打通二者之间的通道
System.out.println("开始与客户端交互数据");
os.write(("欢迎!").getBytes());
InputStream is = client.getInputStream();//接收来自客户端的消息
byte[] buf= new byte[1024] ;//定义 1024个字节数组的缓冲区
int len = is.read(buf); //将数读到缓冲区
System.out.println(new String(buf,0,len));//将缓冲区数据读出
Thread.sleep(5000);
System.out.println("结束与客户端交互数据");
os.close();
is.close();
client.close();//监听套接字关了
}
}
客户端的,后运行
import java.io.*;
import java.net.*;
public class Example005 {
public static void main(String[] args) throws Exception {
// TODO 自动生成的方法存根
new TCPClient().connect();
}
}
//TCP客户端
class TCPClient{
private static final int PORT =7765;
public void connect() throws Exception{
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));//将缓冲区数据读出
OutputStream os=client.getOutputStream();
os.write(("热烈欢迎!").getBytes());
os.close();
is.close();
client.close();
}
}