Java Socket
可以实现互相监听、互发消息,需要先运行服务器端,在运行客户端!
服务器端实现代码:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("服务器已启动");
Socket s = ss.accept();
Scanner in = new Scanner(System.in);
String temp;
//构建IO流
while(true){
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String mess = br.readLine();
System.out.println("客户端>> "+mess);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
System.out.println("请输入发送消息内容:");
temp=in.next();
String str = temp+"\n";
bw.write(str);
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端实现代码:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1",8888);
System.out.println("客户端IP:"+s.getLocalAddress()+" 端口"+s.getPort());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("请输入发送消息内容:");
String temp=scanner.next();
bw.write(temp+"\n");
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("服务器>> "+br.readLine());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行截图: