2013-10-04 189 views
0

我正在尝试在处理中创建客户端 - 服务器通信。 这是server.pde的一个简化版本:处理(多线程)套接字服务器新服务器套接字

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和牵引环应该不断尝试接受的客户。

问题是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.*/ 
另一个“全球” /场的相同签名

Java会优先考虑本地的!

正确的做法:

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”... –