服务端:
public class Server {
public static void main(String [ ] args){
try {
//1、建立服务端
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("-------服务器等待客户端链接--------");
//2、启动服务端
Socket socket = serverSocket.accept();
System.out.println("客户端"+ socket.getInetAddress().getHostAddress()+"链接成功");
//3、获取输入流,读取客户端信息
InputStream inputStream = socket.getInputStream();//获取输入流
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//将字节流转换字符流
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//为字符流建立缓冲区
String line = null;
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
socket.shutdownInput();
//4、获取输出流,响应客户端
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.write("欢迎你!");
printWriter.flush();
socket.shutdownOutput();
//5、关闭相关资源
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
public class Client {
public static void main(String [] args){
try {
//1、创建客户端socket,指定服务器地址和端口号
Socket socket = new Socket("localhost",8888);
//2、获取输出流,向服务器发送信息
OutputStream outputStream = socket.getOutputStream();//字节流
PrintWriter printWriter = new PrintWriter(outputStream);//将字节流包装为打印流
printWriter.write("用户名:123; 密码:123");
printWriter.flush();
socket.shutdownOutput();
//3、获取输入流,读取客户端响应的消息
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
socket.shutdownInput();
//4、关闭资源
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}