2015-10-29 65 views
2

我在玩一个简单的ClientServer应用程序使用套接字,我试图在控制台打印一条消息,并得到服务器的响应,但什么也没有显示出来,我对套接字相当陌生所以我认为我有一个逻辑错误。这是一个简单的应用程序,我希望客户端提示用户一个命令(在我的情况下,输入字符串,服务器将执行基于'th字符的操作),将其发送到服务器,并显示服务器响应。我很确定我的客户端不正确,有人能指出我为什么不能从客户端控制台写入任何东西。java套接字编程聊天

package socketProgramming; 
     import java.io.*; 
     import java.net.*; 

public class MyClient { 

     @SuppressWarnings("resource") 
     public static void main(String[] args) { 
      // TODO Auto-generated method stub 
      Socket socket= new Socket(); 
      BufferedReader in = null; 
      String msg; 
      int port = 2222; 

      try { 

       System.out.println("CLient wants to connect on port: "+port); 

       socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port); 
       System.out.println("The client is connected"); 
      } catch (UnknownHostException e) { 
         System.exit(1); 
      } catch (IOException e) { 
        System.out.println("connect failed"); 
         System.exit(1); 
      } 

      try{ 
       BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        PrintStream output = new PrintStream(socket.getOutputStream()); 
        String text = null; 
      output.print(text); 

      while ((text = input.readLine()) != null){ 
       System.out.println("Client "+text); 

      } 


       socket.close(); 
       System.out.println("Client Exiting"); 
      } 
      catch(IOException e) { 
       System.out.println(e); 
      }} 


     } 

package socketProgramming; 

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



public class MyServer { 

    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 

     String msg = ""; 
     ServerSocket sSocket = null; 
     Socket clientSocket; 
     int port = 2222;//Integer.parseInt(args[0]); 
     try{ 
      sSocket = new ServerSocket(port); 

     } catch(IOException e){ 
      System.out.println(e); 
     } 

     while(true){ 
      try {// listen for a connection from client and accept it. 
       System.out.println("Server is listenning on host: " 
         +InetAddress.getLocalHost().getHostAddress() +"" 
           + " and on port: "     
           + port); 

       clientSocket = sSocket.accept(); 
       System.out.println("Connection accepted"); 
       BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 

       // PrintWriter out = 
         // new PrintWriter(clientSocket.getOutputStream(), true); 

       PrintStream output = new PrintStream(clientSocket.getOutputStream()); 

       msg = input.readLine(); 
       if(msg != null){ 
        if(msg.charAt(12)=='4'){ 

         System.out.println("reading message "+msg+" "); 
         output.print("Bye"); 
         sSocket.close(); 
         System.out.println("Server exits"); 
        }else{ 
         if(msg.charAt(12)=='0'){ 

          System.out.println("reading message "+msg+" "); 
          output.print("OK"); 
         }else if (msg.charAt(12)=='1'){ 

          System.out.println("reading message "+msg+" "); 

          //Should return IP address 
          output.print(clientSocket.getInetAddress()); 
         }else if (msg.charAt(12)=='2'){ 

          System.out.println("reading message "+msg+" "); 
          for(int i = 1; i<=10; ++i){ 

           output.print(i); 
           output.print(" "); 
           } 

          }else if (msg.charAt(12)=='3'){ 


           System.out.println("reading message "+msg+" "); 
           output.print("GOT IT"); 


          }else{ 
           System.out.println("*******************"); 
          } 

         } 



        } 
        sSocket.close(); 
        System.out.println("Server exits"); 
       } 



      catch(IOException e) { 
       System.out.println("accept failed"); 
       System.exit(1); 
      } 

     System.out.println("Hello world"); 
    } 


    } 
    } 
+0

你能详细说明谁是想要开始的消息,以及如何? – Linus

+0

如果他的客户发送类似'CCCCCCCC type0 4567322 X'的东西,因为'12th'字符是0 print'Bye'或任何东西。希望它更清楚一点 – Bobby

+0

嗯,我相信我找到了套接字问题的答案。你可能仍然有问题,因为打印一个'null'字符串会产生一个''null''字符串,但是希望你能诊断任何进一步的问题。 – Linus

回答

2

我花了一些自由度与你的代码,并改变了一下。它绝不是你所提供的完美版本;但是,它应该让你指出正确的方向。这些都被解决了的问题:

  • MyClient从来没有提示用户输入。
  • MyServer正在发送没有换行符的字符串。 MyClient期待带有换行符的字符串。
  • 在MyServer中,主套接字在循环底部被关闭。我相信你打算关闭客户端套接字,以便服务器将循环并处理另一个客户端。
  • 在MyServer中,您正在检查用户输入的第13个字符(因为您正在为字符串的第12个字节(从零开始)编制索引,所以我使用强制保护来检查字符串的第13个字节短。
  • 再次,我只是纠正一些问题在你的代码。我可能已经改变了它超出了你的真正目标其实是这些例子的目的是让你去对你的方式...

MyClient .java:

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

public class MyClient { 

    @SuppressWarnings("resource") 
    public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Socket socket = new Socket(); 
    int port = 2222; 

    try { 

     System.out.println("CLient wants to connect on port: " + port); 

     socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port); 
     System.out.println("The client is connected"); 
    } catch (UnknownHostException e) { 
     System.exit(1); 
    } catch (IOException e) { 
     System.out.println("connect failed"); 
     System.exit(1); 
    } 

    try { 
     BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
     PrintStream output = new PrintStream(socket.getOutputStream()); 

     // Get a line of input from the user. 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String inputFromUser = br.readLine(); 

     // Send that line of input to MyServer. 
     output.println(inputFromUser); 

     // Print out the response from MyServer. 
     System.out.println("SERVER RESPONSE: " + input.readLine()); 

     socket.close(); 
     System.out.println("Client Exiting"); 
    } catch (IOException e) { 
     System.out.println(e); 
    } 
    } 

} 

MyServer.java:

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

public class MyServer { 

    public static void main(String[] args) throws IOException { 
    // TODO Auto-generated method stub 

    String msg = ""; 
    ServerSocket sSocket = null; 
    Socket clientSocket; 
    int port = 2222;// Integer.parseInt(args[0]); 
    try { 
     sSocket = new ServerSocket(port); 

    } catch (IOException e) { 
     System.out.println(e); 
    } 

    while (true) { 
     try {// listen for a connection from client and accept it. 
     System.out.println("Server is listenning on host: " + InetAddress.getLocalHost().getHostAddress() + "" + " and on port: " 
      + port); 

     clientSocket = sSocket.accept(); 
     System.out.println("Connection accepted"); 
     BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 

     // PrintWriter out = 
     // new PrintWriter(clientSocket.getOutputStream(), true); 

     PrintStream output = new PrintStream(clientSocket.getOutputStream()); 

     msg = input.readLine(); 
     if (msg != null) { 
      if (msg.length() > 12 && msg.charAt(12) == '4') { 

      System.out.println("reading message " + msg + " "); 
      output.println("Bye"); 
      System.out.println("Server exits"); 
      } else { 
      if (msg.length() > 12 && msg.charAt(12) == '0') { 

       System.out.println("reading message " + msg + " "); 
       output.println("OK"); 
      } else if (msg.length() > 12 && msg.charAt(12) == '1') { 

       System.out.println("reading message " + msg + " "); 

       // Should return IP address 
       output.println(clientSocket.getInetAddress()); 
      } else if (msg.length() > 12 && msg.charAt(12) == '2') { 

       System.out.println("reading message " + msg + " "); 
       for (int i = 1; i <= 10; ++i) { 

       output.println(i + " "); 
       } 

      } else if (msg.length() > 12 && msg.charAt(12) == '3') { 

       System.out.println("reading message " + msg + " "); 
       output.println("GOT IT"); 

      } else { 
       System.out.println("*******************"); 

       // Invalid question from client, I guess. 
       output.println("HUH?"); 
      } 

      } 

      // Make sure output is flushed to client. It will be, but 
      // just in case... 
      output.flush(); 
     } 

     // We're done with this client. Close his socket. 
     clientSocket.shutdownOutput(); 
     clientSocket.close(); 
     System.out.println("Closed client socket"); 
     } 

     catch (IOException e) { 
     System.out.println("accept failed"); 
     e.printStackTrace(); 
     System.exit(1); 
     } 

     System.out.println("Hello world"); 
    } 

    } 
} 
+0

谢谢!!!!!! – Bobby

2

问题是没有人真的发送任何行。这是你的客户做什么:

output.print(text); //sends null 
while ((text = input.readLine()) != null){ //waits to receive a line 

这最后一部分是你的客户端停止,因为它等待输入,服务器永远不会发送。因此,这里的服务器停止其中:

msg = input.readLine(); //waits to recieve a line 

它从来没有在null读取,因为你没有发线(例如用'\n'结束)。您可以通过用output.println()呼叫替换您的output.print()来轻松解决此问题,以便您的读者知道该线路已结束并可以立即阅读。

+0

感谢您的解释 – Bobby