模擬用戶登錄的功能 實現客戶發送登錄用戶信息,服務器端顯示登錄信並響應給客戶端登錄成功
服務器端
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8090);
Socket s = ss.accept();
InputStream is=s.getInputStream();
OutputStream os=s.getOutputStream();
BufferedReader br= new BufferedReader(new InputStreamReader(is));
String info=null;
while(!((info=br.readLine())==null)){
System.out.println("我是服務器,客戶登錄信息是"+info);
}
String reply="歡迎你,登錄成功!";
os.write(reply.getBytes());
br.close();
os.close();
is.close();
s.close();
ss.close();
}
}
客戶端
public class Client {
public static void main(String[] args) throws Exception {
Socket socket=new Socket("localhost",8090);
OutputStream os=socket.getOutputStream();
InputStream is=socket.getInputStream();
String info="用戶名:sy;用戶密碼:123456";
os.write(info.getBytes());
socket.shutdownOutput();
String reply=null;
BufferedReader br=new BufferedReader(new InputStreamReader(is));
while(!((reply=br.readLine())==null)){
System.out.println("我是客戶端,服務器的響應爲:"+reply);
}
br.close();
is.close();
os.close();
socket.close();
}
}