1 package demo11; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.net.Socket; 9 10 /** 11 * 模拟用户登录的功能,客户端发送登录信息请求,服务器接收请求并回应 12 * @author BCh_Chen 13 * 14 */ 15 public class LoginClient { 16 public static void main(String[] args) { 17 System.out.println("客户端启动!"); 18 try { 19 //发送请求到服务器 20 //创建一个客户端的Socket 21 Socket socket=new Socket("localhost",8888); 22 //通过输出流发送请求 23 String info="用户名:Tom,密码:123456"; 24 //将字符串打散为字节数组 25 byte[] infos=info.getBytes(); 26 OutputStream os=socket.getOutputStream(); 27 os.write(infos); 28 29 socket.shutdownOutput(); 30 31 //接收服务器回应 32 InputStream is=socket.getInputStream(); 33 BufferedReader br=new BufferedReader(new InputStreamReader(is)); 34 String reply; 35 while((reply=br.readLine())!=null) { 36 System.out.println("服务器信息:"+reply); 37 } 38 39 //释放相应资源 40 br.close(); 41 is.close(); 42 os.close(); 43 socket.close(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 } 48 }
1 package demo11; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.net.ServerSocket; 9 import java.net.Socket; 10 11 public class LoginServer { 12 public static void main(String[] args) { 13 System.out.println("服务器启动!"); 14 try { 15 //接收客户端请求 16 //创建一个Socket 17 ServerSocket serverSocket=new ServerSocket(8888); 18 //使用accept()侦听并接收到此ServerSocket的连接 19 Socket socket=serverSocket.accept(); 20 //获得输入流,获得用户的请求 21 InputStream is=socket.getInputStream(); 22 BufferedReader br=new BufferedReader(new InputStreamReader(is)); 23 String info; 24 while((info=br.readLine())!=null) { 25 System.out.println("客户端信息:"+info); 26 } 27 28 29 //给客户端回应信息 30 String reply="登录成功!"; 31 byte[] replys=reply.getBytes(); 32 OutputStream os=socket.getOutputStream(); 33 os.write(replys); 34 35 //释放相应资源 36 os.close(); 37 br.close(); 38 is.close(); 39 socket.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 }
启动顺序是先启动服务器,再启动客户端。