本帖最后由 黄长利 于 2012-4-11 20:24 编辑
import java.io.*;
import java.net.*;
class LoginClient
{
public static void main(String[] args)throws Exception
{
Socket s = new Socket("172.16.32.202",12345);
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
//InputStream in = s.getInputStream();
BufferedReader bufIf = new BufferedReader(new InputStreamReader(s.getInputStream()));
for(int x=0; x<3; x++)
{
String line = bufr.readLine();
if(line==null)
break;
pw.println(line);
//s.shutdownOutput();
//byte[] buf = new byte[1024];
//int len = in.read(buf);
//String info = new String(buf,0,len);
String info = bufIf.readLine();
System.out.println(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()
{
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....;连接上");
try
{
for(int x=0; x<3; x++)
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
String name = bufr.readLine();
BufferedReader bufwj = new BufferedReader(new FileReader("UserInfo.txt"));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//注意为 true
String info = null;
boolean flag = false;
while((info=bufwj.readLine())!=null)
{
if(name.equals(info))
{
flag = true;
break;
}
}
if(flag)
{
System.out.println(name+":已登录");
pw.println("欢迎您的登陆");
break;
}
else
{
System.out.println(name+":尝试登陆");
pw.println("该用户名不存在");
}
//bufwj.close();
}
s.close();
}
catch (Exception e)
{
throw new RuntimeException("登陆异常");
}
}
}
class LoginServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss = new ServerSocket(12345);
while(true)
{
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
以上是在看到网络编程视频中的一个小练习,开启服务端及客户端之后,在读取客户端键盘输入时,直接 Ctrl+C 结束之后,在服务端为什么没有显示 null:尝试登陆,
跟老师视频中的效果有点不一样,在强制结束客户端之后,会执行 s.close(),相当于在服务端会读取到一个 null,经过判断之后,会输出一个尝试登陆,我这个却没有显示,
找了好久也没找到原因在哪,求助......... |