服务器端:
package src;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
//实现简单的一对一聊天室
public static void main(String[] args) throws IOException {
//1.设置网络端口
ServerSocket server=new ServerSocket(8829);
//2.服务器端套接字用Serversocket.accep返回
System.out.println("等待连接...");
Socket socket=server.accept();
System.out.println("连接成功!");
//3.I/O 输入输出
DataInputStream dis=new DataInputStream(socket.getInputStream());
DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
Scanner sc=new Scanner(System.in);
while (true){
dos.writeUTF("欢迎你"+socket.getInetAddress());
System.out.println(dis.readUTF());
String s=sc.nextLine();
dos.writeUTF("主机"+s);
dos.flush();
}
}
}
客户端:
package Client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Client {
//客户端
public static void main(String[] args)throws IOException {
//套接字
Socket socket=new Socket("192.168.111.130",8829);
System.out.println("已连接主机"+socket.getInetAddress());
//I/O输入输出
DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
DataInputStream dis=new DataInputStream(socket.getInputStream());
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("主机:"+dis.readUTF());
String s=sc.nextLine();
dos.writeUTF("客户端1:"+s);
dos.flush();
}
}
}