标签:协议 服务器 try iter [] get col 输入 void
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; /** * 服务器端 * */ public class LoginServer { public static void main(String[] args) { try { //1.建立一个服务器Socket(ServerSocket)绑定指定端口并开始监听 ServerSocket serverSocket=new ServerSocket(8800); //2.使用accept()方法阻塞等待监听,获得新的连接 System.out.println("等待连接"); Socket socket=serverSocket.accept(); System.out.println("已接收到连接,开始处理请求....."); //3.获得输入流 InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); //获得输出流 OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os); //4.读取用户输入信息 String info=null; while(!((info=br.readLine())==null)){ System.out.println("我是服务器,用户信息为:"+info); } //给客户一个响应 String reply="welcome!"; pw.write(reply); pw.flush(); //5.关闭资源 pw.close(); os.close(); br.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStream; 6 import java.io.PrintWriter; 7 import java.net.Socket; 8 import java.net.UnknownHostException; 9 10 /** 11 * 客户端 12 * */ 13 public class LoginClient { 14 public static void main(String[] args) { 15 try { 16 //1.建立客户端Socket连接,指定服务器的位置以及端口 17 Socket socket=new Socket("localhost",8800); 18 //2.得到Socket的读写流 19 OutputStream os=socket.getOutputStream(); 20 PrintWriter pw=new PrintWriter(os); 21 //输入流 22 InputStream is=socket.getInputStream(); 23 BufferedReader br=new BufferedReader(new InputStreamReader(is)); 24 //3.利用流按照一定的协议对Socket进行读/写操作 25 String info="用户名:Tom;用户密码:123456"; 26 pw.write(info); 27 pw.flush(); 28 socket.shutdownOutput(); 29 //接受服务器的响应并打印显示 30 String reply=null; 31 while(!((reply=br.readLine())==null)){ 32 System.out.println("我是客户端,服务器的响应为:"+reply); 33 } 34 //4.关闭资源 35 br.close(); 36 is.close(); 37 pw.close(); 38 os.close(); 39 socket.close(); 40 } catch (UnknownHostException e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } catch (IOException e) { 44 // TODO Auto-generated catch block 45 e.printStackTrace(); 46 } 47 48 } 49 }
标签:协议 服务器 try iter [] get col 输入 void
原文地址:https://www.cnblogs.com/kuangyefeige/p/9822803.html