并发登陆的问题
客户端- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.net.UnknownHostException;
-
- public class LoginClient{
- public static void main(String[] args) throws Exception, IOException {
- Socket s=new Socket("192.168.1.100",10006);
- BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
- PrintWriter out=new PrintWriter(s.getOutputStream(),true);
- BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
- for(int x=0;x<3;x++){
- String line=bufr.readLine();//读一次
- if(line==null){
- break;
- }
- out.println(line);//发出去
- String info=bufin.readLine();//读取服务端的反馈信息
-
- System.out.println("info:"+info);//打印反馈信息
- if(info.contains("欢迎")){
- break;
- }
- }
- bufr.close();
- s.close();
- }
- }
复制代码 服务端- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
-
-
- public class LoinServer {
- public static void main(String[] args) throws Exception {
- ServerSocket ss=new ServerSocket(10006);
- while(true){
- Socket s=ss.accept();
- new Thread(new UserThread(s)).start();
- }
- }
- }
- class UserThread implements Runnable{
- private Socket s;
- UserThread(Socket s){
- this.s=s;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- String ip=s.getInetAddress().getHostAddress();
- System.out.println(ip+"...connected");
- try{
- for(int x=0;x<3;x++){
- BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream()));
- String name=bufin.readLine();
- if(name==null){//客户端ctrl+c停止了
- break;
- }
- BufferedReader bufr=new BufferedReader(new FileReader("c:\\user.txt"));
- PrintWriter out=new PrintWriter(s.getOutputStream());
- String line=null;
- boolean flag=false;
- while((line=bufr.readLine())!=null){
- if(line.equals(name) ){
- flag=true;
- break;
- }
- }
- if(flag){
- System.out.println(name+",已登录");
- out.println(name+",欢迎光临");
- break;
- }else{
- System.out.println(name+",尝试登陆");
- out.println(name+",用户名不存在");
-
- }
- }
- s.close();
- }catch(Exception ex){
- throw new RuntimeException(ip+"校验失败");
- }
- }
- }
复制代码 |
|