本帖最后由 廖力 于 2012-11-13 12:36 编辑
网络编程视频 我看到tcp那里,跟着老师打出代码,用eclipse达不到开两个控制台的效果,而且也出现不了老师那效果。
改用控制台,就报下面那个错误,这是为什么呢?还想问问你们都是怎么做这示例的呢?
贴上代码
file:LoginSer- public class LoginSer {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ServerSocket ss;
- try {
- ss = new ServerSocket(10008);
-
-
- while(true){
- Socket s = ss.accept();
- new Thread(new UserThread(s)).start();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- class UserThread implements Runnable{
- private Socket s;
- public UserThread (Socket s){
- this.s = s;
- }
-
- @Override
- 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();
- BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));
- String line = null;
- boolean flag = false;
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
- while((line=bufr.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 +",用户名不存在");
- }
- }
-
-
- }catch (Exception e){
- throw new RuntimeException(ip+" 检验失败");
- }
-
-
- }
-
-
- }
复制代码 file LoginClient.java- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.io.*;
- public class LoginClient {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Socket s;
- try {
- s = new Socket("127.0.0.1",10008);
-
-
- BufferedReader bufr =
- new BufferedReader(new InputStreamReader(System.in));
-
- PrintWriter out = new PrintWriter(s.getOutputStream());
-
- 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();
-
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码 |