【问题标题】:java socket programming chatjava socket编程聊天
【发布时间】:2015-10-29 02:35:03
【问题描述】:

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

 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");
    }


    }
    }

【问题讨论】:

  • 您能否详细说明谁应该开始发送消息以及如何发送消息?
  • 如果他的客户发送类似CCCCCCCC type0 4567322 X 的东西,因为12th 字符是0 print Bye 或任何东西。希望它更清楚一点
  • 好吧,我相信我找到了套接字问题的答案。您可能仍然遇到问题,因为打印 null 字符串会导致 "null" 字符串,但希望您诊断出任何进一步的问题。

标签: java sockets


【解决方案1】:

我对您的代码进行了一些改动,并对其进行了一些更改。它绝不是您提供的完美版本。但是,它应该让您指向正确的方向。这些是解决的问题:

  • 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");
    }

  }
}

【讨论】:

    【解决方案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.print() 调用替换为 output.println() 调用来轻松解决此问题,以便您的读者知道该行已经结束并且可以立即阅读。

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2019-01-11
      • 2013-10-21
      • 2020-12-15
      相关资源
      最近更新 更多