2012-08-30 157 views
-1

因此,我编写了一个简单的Socket程序,它将消息从客户端发送到服务器程序,并且想知道什么是正确的过程来测试它?我的客户机和服务器机器都在Ubuntu 12.04上运行,并且我可以远程连接到它们两个。测试套接字程序

对于我实例化客户端套接字(testSocket)时的客户端代码,是否使用其IP地址和端口号或服务器IP地址和端口号?

这里是代码的客户:

public static void main(String[] args) throws UnknownHostException, IOException 
{ 
    Socket testSocket = null; 
    DataOutputStream os = null; 
    DataInputStream is = null; 

    try 
    { 
     testSocket = new Socket("192.168.0.104", 5932); 
     os = new DataOutputStream(testSocket.getOutputStream()); 
     is = new DataInputStream(testSocket.getInputStream()); 
    } 
    catch (UnknownHostException e) 
    { 
     System.err.println("Couldn't find Host"); 
    } 
    catch (IOException e) 
    { 
     System.err.println("Couldn't get I/O connection"); 
    } 

    if (testSocket != null && os != null && is != null) 
    { 
     try 
     { 
      os.writeBytes("Hello Server!\n"); 

      os.close(); 
      is.close(); 
      testSocket.close(); 

     } 

     catch (UnknownHostException e) 
     { 
      System.err.println("Host not found"); 
     } 
     catch (IOException e) 
     { 
      System.err.println("I/O Error"); 
     } 
    } 

} 

这里是服务器代码:

public static void main(String[] args) 
{ 
    String line = new String() ; 


    try 
    { 
     ServerSocket echoServer = new ServerSocket(5932); 

     Socket clientSocket = echoServer.accept(); 

     DataInputStream is = new DataInputStream(clientSocket.getInputStream()); 
     PrintStream os = new PrintStream(clientSocket.getOutputStream()); 

      while (true) 
      { 
      line = is.readLine(); 
      os.println(line); 
      } 
    } 
    catch (IOException e) 
    { 
     System.out.println(e.getMessage()); 
    } 

} 

我是新来的插座和不知道我应该会看到什么。我在终端上编译了两个程序,但不知道我应该先运行哪一个程序,还是需要同时启动?

谢谢

+0

您应该先启动服务器,以便客户端有连接的东西。在客户端中,您可以指定服务器的IP地址及其正在侦听的端口。 –

+0

而对于ServerSocket我使用相同的端口号? – Nick

+0

是的。你有没有试过这个?如果您看到错误,请发布。 –

回答

1

您的服务器正在无限循环中运行。避免这种情况。 您必须重新启动计算机。

while (true) 
      { 
      line = is.readLine(); 
      os.println(line); 
      } 

尝试

while (!line.equals("Hello Server!")) 
      { 
      line = is.readLine(); 
      os.println(line); 
      } 

首先运行该服务器。 echoServer.accept();等待连接。当它获得第一个连接时,

+0

*您必须重新启动计算机* ...真的吗? –

+0

这似乎工作,但不是os.println(线);应该返回“Hello Server!”信息? – Nick

+0

客户端完成时间。所以os.printline(行)不会做任何事情。在客户端写入字节后,您可以在客户端添加相同的代码以等待“Hello服务器”消息。 –

0

http://docs.oracle.com/javase/tutorial/networking/sockets/这是一个简短的java教程,介绍如何使用套接字,还可以学习如何制作一次可以接受多个连接的服务器。本教程解释了您始终需要首先启动服务器,这只是合乎逻辑的。您应该使用线程来管理连接,然后关闭它们以便高效地使用资源