本帖最后由 李慧声 于 2013-10-4 21:35 编辑
各位看看 这个是毕姥爷第24天里面的关于tcp传输的最后一个例子,自己模仿写的,不知道哪里错了,求指点- class LoginClient
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("127.0.0.1", 10000);
- 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();
- }
- }
- class UserThread implements Runnable
- {
- private Socket s;
- UserThread(Socket s)
- {
- this.s = s;
- }
- public void run()
- {
- try {
- BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));
- for(int x = 0; x < 3; x++)
- {
- BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
- String name = bufIn.readLine();
- String line = null;
-
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
- boolean flag = false;
- while((line = bufr.readLine()) != null)
- {
- if(line.equals(name))
- {
- flag = true;
- System.out.println("name === " + name + "line == " + line);
- break;
- }
- }
- if(flag)
- {
- System.out.println(name + ", 已登录");
- out.println(name + ",欢迎光临");
- break;
- }
- else
- {
- System.out.println(name + ", 正在尝试登录");
- out.println(name + ",用户不存在");
- }
- }
- bufr.close();
- s.close();
- }
- catch (Exception e) {
- throw new RuntimeException("失败");
- }
- }
- }
- class LoginServer
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10000);
- while(true)
- {
- Socket s = ss.accept();
- new Thread(new UserThread(s)).start();
- }
- }
- }
复制代码 user.txt中的内容
zhangsan
lisi
wangwu
sunba
zhouqi
我的执行结果:
|
|