使用ServerSocket创建TCP服务端
ServerSocket创建服务端,监听来自客服端发送过来信息。
public ServerSocket(int port)用于指定端口,有效的数值 0 ~ 65535
public ServerSocket(int port, int backlog) backlog 连接队列长度的参数
ServerSocket(int port, int backlog, InetAddress bindAddr) 存在多个IP的情况使用bindAddr确定ServerSocket绑定的IP
public static void main(String[] args) throws IOException {
//创建监听获取客户端发送信息,定义端口号为3000
ServerSocket serverSocket = new ServerSocket(3000);
while (true){
/*获取接受到信息*/
Socket socket = serverSocket.accept();
/*发送来的消息io流*/
InputStream in = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
/*接受发送来的信息*/
String result = bufferedReader.readLine();
/*打印数据*/
System.out.print(result);
}
}
客服端使用Socket进行通信
public Socket(String host, int port) 创建连接指定远程主机IP和端口
public Socket(String host, int port, InetAddress localAddr, int localPort)创建连接适用于本机有多个ip地址
public void initSocket(){
new Thread(new Runnable() {
@Override
public void run() {
try {
/*创建连接 */
Socket socket=new Socket("192.168.1.5",3000);
// socket.getInputStream(); 获取服务端发送的数据
// socket.getOutputStream() ; 客户端发送数据给服务端
InputStream in = socket.getInputStream() ;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
/*接受发送来的信息*/
String result = bufferedReader.readLine();
/*打印数据*/
System.out.print(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();