本帖最后由 HM汪磊 于 2013-10-14 17:29 编辑
客户端程序
package cn.it.tcp;
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 {
Socket s=new Socket("127.0.0.1",10015);
//读取键盘录入的数据
BufferedReader bufr=
new BufferedReader(new InputStreamReader(System.in));
//写出客户端录入的数据到服务端
PrintWriter pw=new PrintWriter(s.getOutputStream(), true);
//读入服务端返回的数据
BufferedReader bufrIn=
new BufferedReader(new InputStreamReader(s.getInputStream()));
for(int i=0;i<3;i++){
String line=bufr.readLine();
if(line==null){
break;
}
pw.println(line);
String info=bufrIn.readLine();
if(info.contains("欢迎")){
break;
}
System.out.println("info: "+info);
}
bufr.close();
s.close();
}
}
服务端程序
package cn.it.tcp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
class UserThread implements Runnable{
private Socket s;
UserThread(Socket s){
this.s=s;
}
@Override
public void run() {
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+" ...connect");
try {
for(int i=0;i<3;i++){
//读入客户端传入的数据
BufferedReader bufrIn=
new BufferedReader(new InputStreamReader(s.getInputStream()));
String name=bufrIn.readLine();
if(name==null){
break;
}
//读取文件中的姓名列表
BufferedReader fileIn=
new BufferedReader(new FileReader("names.txt"));
//向客户端返回数据
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
String line=null;
boolean flag=false;
while((line=fileIn.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+" 校验失败");
}
}
}
public class LogInServer {
public static void main(String[] args) throws Exception {
ServerSocket ss=new ServerSocket(10015);
while(true){
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
}复习了下知识,编写这个程序运行时有异常产生找不出来啦,各位帮忙看看,谢谢啦
|