服务端:
package socket; 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; /** *socket服务端 * */ public class TCPServer { public static void main(String[] args) { try { // 创建一个服务端socket实例,并绑定指定端口,同时监听该端口 ServerSocket serversocket = new ServerSocket(7777); //调用accept()启动端口监听,等待客户端请求 System.out.println("服务端已启动,正在监听......"); Socket socket = serversocket.accept();//监听7777端口 InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String info = br.readLine(); while(!"".equals(info) && info != null){ System.out.println("服务端捕获到客户端信息:######"+info); info = br.readLine(); } //关闭相关资源 socket.shutdownInput(); //服务端创建输出流,响应客户端请求 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("用户名密码正确,欢迎登陆"); pw.flush(); //关闭相关资源 socket.shutdownOutput(); //关闭其他资源 pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); serversocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
输出结果:
服务端已启动,正在监听......
服务端捕获到客户端信息:######用户名:admin 密码:1234
客户端:
package socket; 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; import java.net.UnknownHostException; public class TCPClient { public static void main(String[] args) { try { //创建客户端socket,指定服务端地址和端口 Socket socket = new Socket("localhost", 7777); //建立一个输出流,用于向服务端发送信息 OutputStream os = socket.getOutputStream(); //创建一个打印流并包装输出流 PrintWriter pw = new PrintWriter(os); pw.write("用户名:admin 密码:1234"); pw.flush();//刷新缓存 //关闭资源 socket.shutdownOutput(); //创建输入流,用于读取服务端响应信息 InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String serinfo = br.readLine(); while(!"".equals(serinfo) && serinfo != null){ System.out.println("客户端获取服务端响应信息:*****"+serinfo); serinfo = br.readLine(); } socket.shutdownInput(); br.close(); isr.close(); is.close(); pw.close(); os.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
输出结果:
客户端获取服务端响应信息:*****用户名密码正确,欢迎登陆
时间: 2024-11-10 07:56:00