本帖最后由 贠(yun)靖 于 2012-3-30 00:54 编辑
import java.io.*;
import java.net.*;
class LoginClient24_3
{
public static void main(String[] args)throws Exception
{
Socket s = new Socket("192.168.237.1",1111);
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);
//s.shutdownOutput(); 我不添加这句就客户端和服务端就都等待了,但我看毕老师也没加这句啊 加了后不等待 但又有心的问题产生了 好纠结 String str = bufIn.readLine();
System.out.println("输入的信息:"+str);
if(str.contains("欢迎"))
break;
}
bufr.close();
s.close();
}
}
class LoginServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss = new ServerSocket(1111);
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;
}
public void run()
{
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)
break;
BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
String line = null;
boolean flag = false;
while((line=bufIn.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 e)
{
throw new RuntimeException(ip+"登录失败");
}
}
} |
|