java socket编程聊天

时间:2015-10-29 02:35:04

标签: java sockets

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

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


    }
    }

2 个答案:

答案 0 :(得分: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");
    }

  }
}

答案 1 :(得分: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()来电,轻松解决此问题,以便您的读者知道该行已结束,现在可以阅读。