这次的功能就是两台电脑之间可以实现对骂
那就直接上手了。
需要用到多线程和网络编程
1. Server
public class Server6666 {
public static void main(String[] args) throws IOException {
System.out.println("server is runing ....");
//开启一个端口为6666的服务
ServerSocket ss = new ServerSocket(6666);
Scanner sc = new Scanner(System.in);
//获取客户端
Socket c = ss.accept();
sendMsg(sc, c);
acceptMsg(c);
}
//接受消息并且打印消息的方法
public static void acceptMsg(Socket c) {
new Thread(()->{
try {
InputStream inputStream = c.getInputStream();
DataInputStream dii = new DataInputStream(inputStream);
while (true){
System.out.println(c.getRemoteSocketAddress()+":"+dii.readUTF());
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
//发送消息的方法
public static void sendMsg(Scanner sc, Socket c) {
new Thread(()-> {
try {
OutputStream outputStream = c.getOutputStream();
DataOutputStream dis = new DataOutputStream(outputStream);
while (true) {
dis.writeUTF(sc.next());
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
然后就是客户端
2. Client
public static void main(String[] args) throws IOException {
System.out.println("client is runing...");
Socket c = new Socket("localhost", 6666);
Scanner sc = new Scanner(System.in);
Server6666.sendMsg(sc, c);
Server6666.acceptMsg(c);
}
注意: 启动顺序是先启动server然后再启动客户端
你可能注意到了为啥客户端的代码为啥这么少啊,主要是我这里把方法都封装到了Server中。所以代码才少