2012-11-26 2 views
2

그래서 소켓을 사용하여 간단한 클라이언트 서버 프로그램을하고 있어요. 대부분 내가 KnockKnockServer의 코드를했다하지만 난 스레드를간단한 클라이언트/서버 소켓 응용 프로그램 SocketException : 연결 재설정

import java.net.*; 
import java.io.*; 

public class HelpMeServer { 
public static void main(String[] args) throws IOException { 
    Database db=new Database(); 
    ServerSocket serverSocket = null; 
    try { 
     serverSocket = new ServerSocket(50000); 
     System.out.println("Listening on port 911"); 
    } catch (IOException e) { 
     System.err.println("Could not listen on port: 911."); 
     System.exit(1); 
    } 

    Socket clientSocket = null; 
    try { 
     clientSocket = serverSocket.accept(); 
     System.out.println("incomig"); 
    } catch (IOException e) { 
     System.err.println("Accept failed."); 
     System.exit(1); 
    } 
    System.out.println("getting printwriter and bufferedreader"); 
    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
    BufferedReader in = 
     new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
    String inputLine, outputLine; 


    Protocol kkp = new Protocol(db); 
    // initiate conversation with client 
    System.out.println("listening.."); 
//Here the exception is thrown. 
    while ((inputLine = in.readLine()) != null) { 
     kkp.processInput(inputLine); 
     //if (outputLine.equals("Bye.")) 
      //break; 
    }  out.close(); 
    in.close(); 
    clientSocket.close(); 
    serverSocket.close(); 
} 
} 
import java.net.*; 
import java.io.*; 

public class Protocol { 
private static final int WAITING = 0; 
private static final int REGISTERING = 1; 
private static final int LOGIN = 2; 

private int state = WAITING; 
private Database db; 
private String email; 
private String password; 
public Protocol(Database db) 
{ 
    this.db=db; 
    email=null; 
    password=null; 
} 
public void processInput(String theInput) { 
    System.out.println("Cliet: "+theInput); 


    if (state == WAITING) { 
     if(theInput.equals("register")) 
      { 
      state=REGISTERING; 
      System.out.println("set state to registering"); 
      } 
     else if(theInput=="login"){ 
      state=LOGIN; 
      System.out.println("set state to registering"); 
     } 
     } 


    else if(state == REGISTERING) 
    { 
     if(email==null) { 
      email=theInput; 
      System.out.println("set email to "+email); 
     } 
     else { 
      password=theInput; 
      System.out.println("saving "+email); 
      db.addUser(new String(email), new String(password)); 
      password=null; 
      email=null; 
      state=WAITING; 
     } 
    } 
} 
} 
import java.io.*; 
import java.net.*; 

public class NetworkingThread extends Thread{ 

Socket kkSocket; 
PrintWriter out; 
BufferedReader in; 
public void run() 
    { 
    kkSocket = null; 
    out = null; 
    in = null; 

    try { 
     kkSocket = new Socket("localhost", 50000); 
     out = new PrintWriter(kkSocket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); 
    } catch (UnknownHostException e) { 
     System.err.println("Don't know about host: taranis."); 
     System.exit(1); 
    } catch (IOException e) { 
     System.err.println("Couldn't get I/O for the connection to: taranis."); 
     System.exit(1); 
    } 

} 
public void close() 
{ 
    out.close(); 
    try { 
     in.close(); 
     kkSocket.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
public void write(String s) 
{ 
    out.println(s); 
    out.flush(); 
} 
} 

public class go { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
     NetworkingThread n=new NetworkingThread(); 
    n.start(); 
    n.write("register"); 
    n.write("[email protected]"); 
    n.write("password"); 
    n.close(); 

} 

} 

내 오류 (나중에 안드로이드 응용 프로그램에서 사용하기 원하기 때문에이 나를 ​​위해 필요)를 사용하여 클라이언트를 구현 :

Exception in thread "main" java.net.SocketException: Connection reset 
at java.net.SocketInputStream.read(Unknown Source) 
at java.net.SocketInputStream.read(Unknown Source) 
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source) 
at sun.nio.cs.StreamDecoder.implRead(Unknown Source) 
at sun.nio.cs.StreamDecoder.read(Unknown Source) 
at java.io.InputStreamReader.read(Unknown Source) 
at java.io.BufferedReader.fill(Unknown Source) 
at java.io.BufferedReader.readLine(Unknown Source) 
at java.io.BufferedReader.readLine(Unknown Source) 
at HelpMeServer.main(HelpMeServer.java:34) 

이 코드를 가져 와서 NetworkThread 실행 메서드를 넣으면 오류가 사라집니다. 하지만 난, 내가 외부

n.write("register"); 
n.write("[email protected]"); 
n.write("password"); 
n.close(); 

에서 내가 조언 (같은 장소에서 계속 같은 오류)

import java.net.*; 
import java.io.*; 

public class HelpMeServer { 
public static void main(String[] args) throws IOException { 
    Database db=new Database(); 
    ServerSocket serverSocket = null; 
    try { 
     serverSocket = new ServerSocket(50000); 
     System.out.println("Listening on port 911"); 
    } catch (IOException e) { 
     System.err.println("Could not listen on port: 911."); 
     System.exit(1); 
    } 

    while(true) 
    { 
    Socket clientSocket = null; 
    try { 
     clientSocket = serverSocket.accept(); 
     System.out.println("incomig"); 
     ClientThread t=new ClientThread(clientSocket,db); 
     t.start(); 
    } catch (IOException e) { 
     System.err.println("Accept failed."); 
     System.exit(1); 
    } 
    } 
    } 
      } 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 


public class ClientThread extends Thread { 

Socket clientSocket; 
Database db; 
public ClientThread(Socket s,Database db) 
{ 
    clientSocket=s; 
    this.db=db; 
} 
public void run() 
{ 
    System.out.println("getting printwriter and bufferedreader"); 
     PrintWriter out; 
     try { 
     out = new PrintWriter(clientSocket.getOutputStream(), true); 
     BufferedReader in = 
     new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
       String inputLine, outputLine; 


       Protocol kkp = new Protocol(db); 
       System.out.println("listening.."); 
       while ((inputLine = in.readLine()) != null) {//error! 
        kkp.processInput(inputLine); 
        //if (outputLine.equals("Bye.")) 
         //break; 
       } 
       out.close(); 
       in.close(); 
       clientSocket.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

} 

    } 
에 따라 이루어 때문에 변경이 메소드를 호출 할 필요가 내 응용 프로그램이 사용할 수 없습니다

답변

0

이 작업을하려면 serverSocket.accept()을 루프에 넣어야합니다. 그 순간에 하나의 메시지를 얻은 다음 서버 소켓을 닫으므로 서버 소켓을 수신하지 않기 때문에 이후에 서버에 연결하려고하면 거부됩니다.

+0

정확히 루프 모양을 표시해야합니까? –

+0

소켓 프로그래밍에 대한 Java 자습서를 읽었다 고합니다. 페이지 끝에는 "여러 클라이언트 지원"이라는 단락이 있으며 어떻게 작동하는지 설명합니다. –

+0

글쎄 나는 단락에 따라 그것을 변경하지만 여전히 같은 오류가 발생합니다. –