2013-10-04 6 views
0

처리 중에 클라이언트 - 서버 통신을 만들려고합니다. 이것은 server.pde의 제거 버전 : 설치 루프가 지속적으로 받아들이는 클라이언트를 시도해야 ServerSocket과 무승부 루프를 초기화하도록되어처리 (멀티 스레딩) 소켓 서버 new serverSocket

cThread thread; 
ServerSocket socket1; 
int main_sid = 0; 
int main_port = 5204; 

void setup() { 
    size(300, 400); 
    try { 
    ServerSocket socket1 = new ServerSocket(main_port); 
    } catch (Exception g) { } 
} 

void draw() { 
    try{ 
      Socket main_cnn = socket1.accept(); 
      thread = new cThread(main_cnn,main_sid,20); 
      thread.start(); 
      println("New client: " + main_cnn.getRemoteSocketAddress() + " Assigned sid: " + main_sid); 
      main_sid++; 

    } catch (Exception g) { } 
} 

class cThread extends Thread { ... 

.

문제는 ServerSocket socket1 = new ServerSocket(main_port); 한 번만 초기화해야하지만이 설정에 적용하면 작동하지 않습니다.

어떻게해야합니까?

답변

2
당신은 필드로 당신은 설정에서 로컬로 선언 옆에 선포

...

당신은 당신이

ServerSocket socket1; 
... 
void setup() 
{ 
... 
    ServerSocket socket1... /* here you want to use the socket above... 
    but you declare a socket variable with the same signature, 
    so to compiler will ignore the field above and will use your local 
    variable... 

    When you try to use the field he will be null because you do not affected 
    your state.*/ 
를했던 것처럼 또 다른 "글로벌"/ 필드의 동일한 서명으로 지역 변수를 선언하면

자바가 로컬에 우선권을 부여합니다!

올바른 방법 :

void setup() 
{ 
    size(300, 400); 
    try 
    {/* now you are using the field socket1 and not a local socket1 */ 
     socket1 = new ServerSocket(main_port); 
    } 
    catch (Exception g) { } 
} 
+0

당신이 '형'을 의미하는에 의해 '서명', 다른 경우에도 발생합니다. 그것은 단지 '우선 순위'가 아닌 범위의 문제입니다. 예외를 무시하는 것에 대해 '옳은'것은 없습니다. – EJP

+0

나는 형식을 되풀이하지 않을거야 ... 내가 서명을 의미 할 때 나는 "socket1"이라고 말하고 싶다. –