服务端:
public class Server {
public static void main(String[] args){
try {
ServerSocket serverSocket = new ServerSocket(10086);
System.out.println("正在监听端口号:10086");
Socket socket = serverSocket.accept();
System.out.println("连接成功,客户端地址:"+socket.getInetAddress().getHostAddress()+":"+socket.getPort());
//输入流
DataInputStream dis = new DataInputStream(socket.getInputStream());
while (true){
String msg = dis.readUTF();
System.out.println("收到信息:"+msg);
if(msg.equals("exit"))break;
}
dis.close();
socket.close();
serverSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
客户端:
public class Client {
public static void main(String[] args){
try {
Socket socket = new Socket("127.0.0.1",10086);
//输出流
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
while (true){
Scanner scanner = new Scanner(System.in);
System.out.print("输入信息:");
String str = scanner.nextLine();
dos.writeUTF(str);
if (str.equals("exit"))break;
}
dos.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
测试过程:
先启动服务端,再启动客户端,在客户端控制台进行输入操作。
客户端控制台:
输入信息:123456
输入信息:abcd
输入信息:exit
服务端控制台:
正在监听端口号:10086
连接成功,客户端地址:127.0.0.1:60178
收到信息:123456
收到信息:abcd
收到信息:exit