2012-07-25 8 views
0

안녕하세요, 저는 동일한 컴퓨터에서 mutltythreaded 서버 프로세스에 연결하는 소켓 클라이언트에 대한 데이터를 얻으려고합니다. 서버 스레드가 올바르게 트리거되고 클라이언트 IP가 괜찮아 지지만 연결을 통해 문자열을 보낼 수없는 것 같습니다. 통해 전송 CLIENTJava 소켓 클라이언트/서버

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package solverapplet; 
import java.io.DataInputStream; 
import java.io.IOException; 
import java.io.PrintStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import java.io.*; 

/** 
* 
* @author me 
*/ 
public class Solverapplet { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // TODO code application logic here 
     Socket s; 
     try { 
      s = new Socket("IP", 4445); 
      System.out.println(s.getPort()); 
      //DataInputStream in = new DataInputStream (s.getInputStream()); 
     BufferedWriter out = new BufferedWriter(
          new OutputStreamWriter(s.getOutputStream())); 
     out.write("gamma"); 
         out.newLine(); 
         out.flush(); 

     } catch (UnknownHostException ex) { 
      Logger.getLogger(Solverapplet.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (IOException ex) { 
      Logger.getLogger(Solverapplet.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } 
} 

서버 THREAD

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package serversideserver; 
import java.io.*; 
import java.net.*; 
import java.security.*; 
import java.util.List; 
import java.sql.*; 
import com.google.gson.Gson; 


class doComms implements Runnable { 
    private Socket server; 

    private String line,input,ip; 

    doComms(Socket server, String ip) { 
     this.server=server; 
     this.ip=ip; 
    } 

    public void run() { 

     input=""; 

     try { 
     // Get input from the client 
     BufferedReader in = new BufferedReader(
          new InputStreamReader(server.getInputStream())); 

     PrintStream out = new PrintStream(server.getOutputStream()); 
     Connection conn = null; 
     try 
      { 
       String userName = "root"; 
       String password = ""; 
       String url = "jdbc:mysql://localhost/test"; 
       Class.forName ("com.mysql.jdbc.Driver").newInstance(); 
       conn = DriverManager.getConnection (url, userName, password); 
       System.out.println ("Database connection established"); 
       // create the java statement 
     Statement st = conn.createStatement(); 

     // ResultSet rs; 
     while((line = in.readLine()) != null && !line.equals(".")) { 
      // Now do the magic. 
     //Data data = new Gson().fromJson(line, Data.class); 
     System.out.println("LINE: " + line); 
     input=line; 
     st.executeUpdate("UPDATE `solvers` SET `online`='1',`ip`='"+ server.getInetAddress().toString().substring(1) +"' WHERE `user`='"+ line +"'"); 

     // input= data.getcmd(); 
      out.println("{\"captcha\":1,\"text\":\"abc\",\"is_correct\":\"true\"}"); 
     } 
      } 
      catch (Exception e) 
      { 
       System.out.println (e.toString()); 
      } 

     // Now write to the client 

     System.out.println("UPDATE `solvers` SET `online`='1',`ip`='"+ server.getInetAddress() +"' WHERE `user`='"+ input +"'"); 
     //out.println("Overall message is:" + input); 

     server.close(); 
     } catch (IOException ioe) { 
     System.out.println("IOException on socket listen: " + ioe); 
     ioe.printStackTrace(); 
     } 
    } 
} 

행은 비어있다. 당신이 타이밍 문제의 비트를 가지고 같은 연결

package serversideserver; 

import java.io.*; 
import java.net.*; 
import java.security.*; 
import java.sql.*; 
/** 
* Title:  Sample Server 
* Description: This utility will accept input from a socket, posting back to the socket before closing the link. 
* It is intended as a template for coders to base servers on. Please report bugs to brad at kieser.net 
* Copyright: Copyright (c) 2002 
* Company:  Kieser.net 
* @author B. Kieser 
* @version 1.0 
*/ 

public class Serversideserver { 

    private static int port=4445,portsolver=4445, maxConnections=0; 
    // Listen for incoming connections and handle them 
    public static void main(String[] args) { 
    int i=0; 

    try{ 
     ServerSocket listener = new ServerSocket(port); 
     Socket server; 

     long counter=0; 
      int counter1=0; 
    int id=0; 
     String ip="uninit"; 
     while((i++ < maxConnections) || (maxConnections == 0)){ 

     server = listener.accept(); 
     counter++; 
     doComms conn_c= new doComms(server,ip); 
     Thread t = new Thread(conn_c); 
     t.start(); 
     //System.out.println("counter "+ (counter % id)); 
     } 
    } catch (IOException ioe) { 
     System.out.println("IOException on socket listen: " + ioe); 
     ioe.printStackTrace(); 
    } 

    } 

} 
+0

거기에 mysql 연결이 있지만 모두 올바르게 연결됩니다. – Evan

+4

여기에 게시하는 것처럼 코드를 작성합니까? 괜찮은 자세를 취하고 적절하게 포맷하면 눈이 아플 수 있습니다! –

+1

서버가 올바르게 호출 되었습니까? 통상, 착신 접속을 받아들이려면 ServerSocket를 사용합니다. 어떻게 서버의 소켓을 초기화합니까? – jeff

답변

1

설립 나는 보인다. 다음은 올바른 타이밍의 코드입니다. 문제의 코드가 불필요하게 삭제되었습니다.

클라이언트 : 클라이언트에서와 같이 소켓에 쓰고 즉시 응용 프로그램을 종료하고 (연결이 끊어졌습니다) 나타납니다. doComms 클래스는 클라이언트에게 다시 쓰고 있었으므로 응답을 읽는 코드를 추가했습니다. 그러나 응답을 기대하지 않았다면 여전히 1 바이트를 읽어야합니다. 이렇게하면 일부 데이터가 아닌 EOF가 있는지 확인할 수 있으며 현재 스레드를 차단하고 연결을 유지합니다.

package solverapplet; 

import java.io.IOException; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import java.io.*; 

/** 
* 
* @author you 
*/ 
public class Solverapplet { 

    /** 
    * @param args the command line arguments 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     Socket s = null; 
     try { 
      // make connection 
      s = new Socket("localhost", 4445); 

      // define streams 
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 

      // write data 
      out.write("gamma"); 
      out.newLine(); 
      out.flush(); 

      // read response 
      String returnData = in.readLine(); 
      System.out.println(returnData); 

     } catch (UnknownHostException ex) { 
      Logger.getLogger(Solverapplet.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (IOException ex) { 
      Logger.getLogger(Solverapplet.class.getName()).log(Level.SEVERE, null, ex); 
     } finally { 
      // close connection 
      s.close(); 
     } 
    } 
} 

서버 : 차라리 연결의 최대 개수가 설정된 후 종료보다 주어진 시간에 연결의 최대 수를 허용하도록 서버를 변경했습니다. 또한 스레드는 데몬이 아닙니다. 당신이 다음 종료를 X 번호 고객 서비스를 제공하려는 경우, 당신은 스레드가 ServerSocket를

package serversideserver; 

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

/** 
* Title:  Sample Server 
* Description: This utility will accept input from a socket, posting back to the socket before closing the link. 
* It is intended as a template for coders to base servers on. Please report bugs to brad at kieser.net 
* Copyright: Copyright (c) 2002 
* Company:  Kieser.net 
* @author B. Kieser 
* @version 1.0 
*/ 

public class Serversideserver { 

    private static int port    =4445; 
    private static int maxConnections =10; 

    private static int connections = 0; 

    synchronized static void connectionClosed() { 
     connections--; 
     Serversideserver.class.notify(); 
    } 

    /** 
    * The blocking mechanism to only allow <code>maxConnections<code> 
    * @throws InterruptedException 
    *  thrown if blocking thread is interupted 
    */ 
    private synchronized static void nextConnection() throws InterruptedException { 
     while(connections>=maxConnections) { 
      Serversideserver.class.wait(); 
     } 
    } 

    public static void main(String[] args) throws InterruptedException { 
     try{ 
      // server socket 
      ServerSocket listener = new ServerSocket(port); 
      // socket 
      Socket socket; 

      // Keep the server alive 
      while(true){ 
       // Blocks if we have reached the max 
       nextConnection(); 

       // Accept connection to client 
       socket = listener.accept(); 

       // define request service 
       doComms conn_c= new doComms(socket,socket.getInetAddress().getCanonicalHostName()); 
       Thread t = new Thread(conn_c); 
       t.setDaemon(false); 

       // run request service 
       t.start(); 
      } 
     } catch (IOException ioe) { 
      System.out.println("IOException on socket listen: " + ioe); 
      ioe.printStackTrace(); 
     } 
    } 
} 

doComms 종료하기 전에 실행을 계속 할 수 있도록하는 메커니즘이 필요합니다 많은이 클래스를 변경하지 ... 난 그냥 그것을 청소 약간의 불필요한 코드 줄이 제거되었습니다.

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package serversideserver; 
import java.io.*; 
import java.net.*; 


class doComms implements Runnable { 
    private Socket socket; 
    private String ip; 

    doComms(Socket socket, String ip) { 
     this.socket = socket; 
     this.ip = ip; 
    } 

    public void run() { 
     try { 
      // Define input/output 
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      PrintStream out = new PrintStream(socket.getOutputStream()); 

      // Process requests until the EOF is found 
      String line; 
      while((line = in.readLine()) != null && !line.equals(".")) { 
       // print input 
       System.out.println("LINE: " + line); 

       // print process line 
       System.out.println("UPDATE `solvers` SET `online`='1',`ip`='"+ ip +"' WHERE `user`='"+ line +"'"); 

       // write response 
       out.println("{\"captcha\":1,\"text\":\"abc\",\"is_correct\":\"true\"}"); 
      } 

      socket.close(); 
     } catch (IOException ioe) { 
      System.out.println("IOException on socket listen: " + ioe); 
      ioe.printStackTrace(); 
     } finally { 
     Serversideserver.connectionClosed(); 
    } 
    } 
} 

희망이

+0

굉장한 친구. 고맙습니다 타이밍은 그것이 보이는 문제였습니다 :) – Evan

0

귀하의 질문은 심각하게 모호 :) 도움이되지만 서버가 클라이언트에 응답 할 수없는 이유를 궁금해하는 경우 클라이언트가 절대 소켓에서 읽지 않습니다 때문입니다.