黑马程序员技术交流社区
标题:
网络编程问题,问题在UserServer注释部分
[打印本页]
作者:
ゞ导火索゛
时间:
2014-6-24 17:14
标题:
网络编程问题,问题在UserServer注释部分
本帖最后由 ゞ导火索゛ 于 2014-6-25 19:26 编辑
package com.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
/*
* 需求:通过客户端向浏览器端进行登陆请求,
* 1,定义客户端
* 2,定义键盘录入。通过主函数的参数进行
* 3、将参数写出到服务器端
* 4,接收服务器的响应
*/
import java.io.*;
import java.net.*;
public class UserClient {
public static void main(String[] args)
{
try
{
Socket client = new Socket(InetAddress.getByName("172.28.170.51"), 10000);
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader bufIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
for(int i=0; i<3; i++)
{
String line = bufr.readLine();
out.println(line);
String info = bufIn.readLine();
System.out.println("info:" + info);
if(info.contains("成功"))
break;
}
client.close();
bufr.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
复制代码
package com.net;
/*
* 需求:
* 1,定义服务器端,
* 2,获取客户端对象
* 3,定义一个线程用于操作多个客户端登陆
* 4,接受客户端的消息,对该user与user.txt中的数据进行遍历比较
* 5,给客户端发送登陆成功或者失败的提示
* 6、 关闭资源
*/
import java.io.*;
import java.net.*;
public class UserServer {
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(10000);
while(true)
{
Socket client = server.accept();
new Thread(new UserThread(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class UserThread implements Runnable
{
private Socket client ;
public UserThread(Socket client)
{
this.client = client ;
}
public void run()
{
String ip = client.getInetAddress().getHostAddress();
System.out.println(ip+".....connected");
try
{
<font color="#ff0000"> /*
* 这四句放在for循环外面怎么结果不一样,不是很明白,
*
* File file = new File("src\\com\\net\\user.txt");
BufferedReader bufr = new BufferedReader(new FileReader(file));
BufferedReader bufIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
*/
</font>
for(int i=0; i<3; i++)
{
File file = new File("src\\com\\net\\user.txt");
BufferedReader bufr = new BufferedReader(new FileReader(file));
BufferedReader bufIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
//客户端消息
String line = bufIn.readLine();
//txt中的消息
String name = null;
boolean flag = false;
while((name=bufr.readLine())!=null)
{
if(name.equals(line))
{
flag = true;
break;
}
}
if(flag)
{
System.out.println(name+",欢迎登陆!!");
out.println(name+",登陆成功");
break;
}
else
{
System.out.println(line+",尝试登陆");
out.println(line + ",该用户不存在");
}
}
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
复制代码
问题在UserServer的注释部分
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2