Socket通信基础——基于TCP的用户登录
来源:互联网 发布:淘宝客服能在家里做吗 编辑:程序博客网 时间:2024/06/01 16:56
服务器端:
1、创建ServerSocket对象,绑定监听端口;
ServerSocket serverSocket = new ServerSocket(5555);2、通过accept()方法监听客户请求,等待客户端的连接;
Socket socket = serverSocket.accept();3、与客户端建立连接以后,通过输入流读取客户端发送的请求信息;
// 获得输入流,读取客户端信息// 字节流InputStream is = socket.getInputStream();// 将字节流转为字符流InputStreamReader isr = new InputStreamReader(is);// 为输入流添加缓存BufferedReader br = new BufferedReader(isr);String info = null;// 循环读取客户端的信息while ((info = br.readLine()) != null) {System.out.println("客户端信息:" + info);}4、通过输出流,向客户端发送响应信息;
// 发送输出流,响应客户端信息OutputStream os = socket.getOutputStream();PrintWriter pw = new PrintWriter(os);pw.write("登录成功");pw.flush();5、关闭相关资源:输入输出流、ServerSocket等。
// 关闭相关资源pw.close();os.close();br.close();isr.close();is.close();socket.close();serverSocket.close();客户端:
1、创建Socket对象,指明需要连接的服务器地址和端口号,与服务器端建立连接;
Socket socket = new Socket("localhost", 5555);2、建立连接以后,通过输出流,向服务器端发送请求信息;
// 获得输出流,向服务器发送信息// 字节输出流OutputStream os = socket.getOutputStream();// 将字节流转为打印流PrintWriter pw = new PrintWriter(os);pw.write("用户名:密码");pw.flush();3、通过输入流获取服务器响应的信息;
// 获得服务器端发送给客户端的输入流InputStream is = socket.getInputStream();InputStreamReader isr = new InputStreamReader(is);BufferedReader br = new BufferedReader(isr);String info = null;while ((info = br.readLine()) != null) {System.out.println(info);}4、关闭相关资源。
// 关闭相关资源br.close();isr.close();is.close();pw.close();os.close();socket.close();
0 0
- Socket通信基础——基于TCP的用户登录
- 基于TCP协议的Socket通信 实现用户登录 以及服务端的相应
- Android基础入门教程——7.6.2 基于TCP协议的Socket通信(1)
- Android基础入门教程——7.6.3 基于TCP协议的Socket通信(2)
- 基于TCP的Socket通信
- 基于TCP的socket通信
- 基于TCP的Socket通信
- Java Socket应用(五)——编程实现基于 TCP 的 Socket 通信
- 【Java Socket】入门系列 3.2.编程实现基于 TCP 的 Socket 通信 — 服务器端和客户端
- C#基于TCP的Socket通信
- 基于ipv6的socket通信(TCP)
- 基于tcp的简单socket通信
- 基于TCP的简单socket通信
- IOS socket基于tcp/udp的通信
- C#基于TCP的Socket通信
- 基于tcp的socket通信程序
- 基于tcp和udp的socket通信
- 基于TCP协议的Socket通信
- CSS3+HTML5表单
- poj 2513 Colored Sticks
- 用python写的多线程网页爬虫
- tar、tar.gz、tar.bz2的区别与用法
- MATLAB学习笔记(二):符号计算(创建符号对象)
- Socket通信基础——基于TCP的用户登录
- POJ 3624 01背包
- centos mysql安装
- Lexicographically minimum string rotation
- JavaScript系列二:变量、数组、流程控制、函数以及事件响应
- 1501171340-蓝桥杯-算法提高 逆序排列
- microsoftoffice2013 破解方法(含有破解工具)
- [leetcode] Valid Parentheses
- Spark的核心概念