接着,实现服务器端对客户端的反馈:
首先是服务器端:
package love.jimo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
/*
* 服务端
*/
try {
//建立服务器端socket,并监听此端口9000
ServerSocket ssket = new ServerSocket(9000);
System.out.println("---服务器端启动---");
//调用accept方法监听,等待客户端连接
Socket sket = ssket.accept();
//获得输入流,并读取客户端信息
InputStream is = sket.getInputStream();
//将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(is);
//缓冲
BufferedReader br = new BufferedReader(isr);
String data = null;
//循环读取
while(null != (data = br.readLine())){
System.out.println("在服务器端收到客户端的信息是:"+data);
}
//关闭socket输入流
sket.shutdownInput();
is.close();
isr.close();
br.close();
sket.close();
ssket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
新增代码为:
<span style="white-space:pre"> </span>//响应客户端的请求
OutputStream os = sket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("我是服务器,欢迎你!");
pw.flush();
//关闭其它资源
os.close();
pw.close();
然后是客户端:
package love.jimo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream.GetField;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
/*
* 客户端
*/
try {
//创建客户端socket,指定服务器地址和端口,localhost代表本机地址
Socket sket = new Socket("localhost",9000);
//获取输出流,向服务器发送信息
OutputStream os = sket.getOutputStream();
//将字节输出流包装为打印输出流
PrintWriter pw = new PrintWriter(os);
pw.write("username:jimo;password:111");
//清空缓存,将消息发送
pw.flush();
//关闭socket输出流
sket.shutdownOutput();
os.close();
pw.close();
sket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
新增代码为:
<span style="white-space:pre"> </span>//接收服务器的反馈
InputStream is = sket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String info = null;
while(null != (info = br.readLine())){
System.out.println("在客户端收到服务器端的反馈是:"+info);
}
//关闭资源
is.close();
isr.close();
br.close();
服务器端的运行不变:
客户端有输出了: