//这是客户端
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public Client() {
try {
Socket s = new Socket("127.0.0.1",9999);
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
InputStreamReader isr2 = new InputStreamReader(s.getInputStream());
BufferedReader br2 = new BufferedReader(isr2);
while (true) {
System.out.println("请输入你对服务器的话");
String info = br.readLine();
pw.println(info);
String res = br2.readLine();
System.out.println("服务器说"+ res);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
}
}
//这是服务器
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Server server =new Server();
}
public Server(){
try {
System.out.println("服务器在9999监听");
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
InputStreamReader isr2 = new InputStreamReader(System.in);
BufferedReader br2 = new BufferedReader(isr2);
while (true) {
String infoFromClient = br.readLine();
System.out.println("客户端发来"+infoFromClient);
System.out.println("请输入你想对客户端说的话");
String response = br2.readLine();
pw.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}