package com.frame.base.TCP;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPSocketServer {
public static void main(String[] args) throws Exception{
/**
* 启动服务端Soecket 注册外放信息交互的端口
*/
ServerSocket serverSocket = new ServerSocket(9999);
//定义Socket对象监听9999端口接收的数据
Socket socket = serverSocket.accept();
System.out.println("IP:"+serverSocket.getInetAddress().getHostAddress()+"__连接上服务端开始接收数据...");
//定义输入流和解析字节数据
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
System.out.println("读取的数据为:"+new String(bytes,0,len));
//关闭客户端
socket.close();
//关闭服务端(可选)
serverSocket.close();
}
}
2.客户端
package com.frame.base.TCP;
import java.io.OutputStream;
import java.net.Socket;
public class TCPSocketClient {
public static void main(String[] args) throws Exception {
/**
* 定义Socket 指定接入服务端的IP和外放端口
*/
Socket socket = new Socket("127.0.0.1", 9999);
/**
* 将请求数据封装到输出流中进行传递
*/
OutputStream out = socket.getOutputStream();
out.write("TCPSocketClient说: 你好服务器".getBytes());
socket.close();
}
}
3.运行结果