Socket类实现客户端与服务器进行通信(1)
一.服务器是已有的server.jar,先把服务器在本地运行起来
server.jar包:
开始菜单打开Windows PowerShell——cd (这里加上server.jar的存放目录)
接着输入 java -jar server.jar将服务器在本地运行起来 看到server start in 9876说明运行成功(9876是服务器程序中指定的运行端口)
二.客服端程序
public class Test1 {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client = new Socket("127.0.0.1", 9876); //public Socket(String host, int port)
System.out.println("建立链接成功!!");
InputStream in = client.getInputStream(); //receive server>>client
OutputStream out = client.getOutputStream(); //send client>>server
PrintWriter pw = new PrintWriter(out);
//读 server>>client
InputStreamReader re = new InputStreamReader(in);
BufferedReader br = new BufferedReader(re);
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
// BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
while (true) {
System.out.println("输入内容:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
pw.write(str+"\r\n");
pw.flush();
String info = "";
String s = null;
s = br.readLine();
info = s;
System.out.println("服务器:" + info);
}
}
}
这里需要注意,必须加上\r\n,因为http协议的结尾标识就是\r\n,省略了就会导致服务器一直以为客户端没结束发送,而一直不做出回应,出于等待状态
三.在eclipse中保存运
客户端处每输入一条语句,服务器就会做出回应