已测试:- import java.net.*;
- import java.io.*;
- class LoginClient
- {
- public static void main(String[] args) throws Exception
- {
- Socket s=new Socket("LocalHost",12007);
- BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
- PrintWriter bufout=new PrintWriter(s.getOutputStream(),true);//没有自动刷新
- BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
- for(int i=0;i<5;i++)
- {
- String line=bufr.readLine();
- //System.out.println(line);
- if(line==null)
- break;
- bufout.println(line);
- //System.out.println(line);
- String info=bufin.readLine();
- System.out.println("info: "+info);
- if(info.contains("欢迎"))
- break;
- }
- bufr.close();
- s.close();
- }
- }
- class ThreadLogin implements Runnable
- {
- private Socket s;
- ThreadLogin(Socket s)
- {
- this.s=s;
- }
- public void run()
- {
- String ip=s.getInetAddress().getHostAddress();
- System.out.println(ip+"....connected");
- try
- {
- for(int i=0;i<5;i++)
- {
- BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
- //System.out.println(bufin.readLine());//去掉这句,连续两次readLine(),下面会readLine会阻塞
- // System.out.println("shui");
- BufferedReader bufr=new BufferedReader(new FileReader("UserName.txt"));
- PrintWriter bufout=new PrintWriter(s.getOutputStream(),true);//同样没有自动刷新
-
- String name=bufin.readLine();
- System.out.println("name="+name);
-
- String line=null;
- boolean flag=false;
- while((line=bufr.readLine())!=null)
- {
- if(line.equals(name))
- {
- flag=true;
- break;
- }
- }
- if(flag)
- {
- System.out.println(name+"已登录");
- bufout.println(name+":欢迎登录");
- break;
- }
- else{//没加{}
- System.out.println(name+"尝试登录服务器");
- bufout.println(name+"不存在");
- }
- }
- s.close();
- }
- catch (Exception e)
- {
- //throw new RuntimeException(ip+"校验失败");
- e.printStackTrace();
- }
- }
- }
- class LoginServer
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss=new ServerSocket(12007);
- while(true)
- {
- Socket s=ss.accept();
- new Thread(new ThreadLogin(s)).start();
- }
- }
- }
- /*
- 好好整理下思路,细心点
- */
复制代码 |