Socket:套接字
流式套接字:基于TCP协议的Socket网络编程
工作方式:
1.客户端A连接到服务器;
2.服务器建立连接并把客户端A添加到列表;
3.客户端B、C...连接;
4.客户端B送出消息到服务器;
5.服务器将信息发送给客户端B、C...。
要点:
1.如何建立客户端与服务器之间的初始连接;
2.如何传送信息到服务器;
3.如何接收来自服务器的信息。
案例:客户端向服务器发送登录请求,服务器收到后回复登录成功信息。
服务器代码:
package com.yh.mySocket; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class LoginServer { public static void main(String[] args) { ServerSocket serversocket = null; Socket socket = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; try { // 创建一个服务器Socket serversocket = new ServerSocket(5000); // 使用accept()等待用户的通信 socket = serversocket.accept(); // 获得输入流,获得相应的用户请求 is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String info; while((info = br.readLine())!=null) { System.out.println(info); } // 获得输出流,给客户端发送请求 os = socket.getOutputStream(); String reply = "登陆成功!"; byte[] replys = reply.getBytes(); os.write(replys); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { // 释放资源 os.close(); br.close(); is.close(); socket.close(); serversocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
客户端代码:
package com.yh.mySocket; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; public class LoginClient { public static void main(String[] args) { Socket socket = null; OutputStream os = null; InputStream is = null; BufferedReader br = null; try { // 创建一个客户端Socket,参数为客户端IP和指定端口号,此处客户端和服务器在同一台电脑,所以IP地址相同 socket = new Socket("localhost",5000); // 通过输出流,给服务器发送请求 os = socket.getOutputStream(); String info = "用户名:YeHuan; 密码:12345"; byte[] infos = info.getBytes(); os.write(infos); // 关闭输出流 socket.shutdownOutput(); // 获得输入流,接收服务器请求 is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String reply; while((reply = br.readLine())!=null) { System.out.println(reply); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { is.close(); os.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }