【问题标题】:Java Client and Server connected but not communicatingJava 客户端和服务器已连接但未通信
【发布时间】:2017-02-19 18:46:26
【问题描述】:

所以我正在尝试创建一个客户端 - 服务器聊天应用程序,并且我已经编写了该程序。客户端和服务器通过本地主机上的公共端口(5000)连接。服务器和客户端连接(控制台通过 system.out 确认)但是当我提示服务器向客户端发送 println 以提示用户输入用户名时,没有任何反应。请帮忙。

客户:

//ChatClient.java

import javax.swing.*;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.*;

import java.net.Socket;

public class ChatClient {

    static JFrame chatWindow = new JFrame("OneOh");

    static JTextArea chatArea = new JTextArea(20, 50);

    static JTextField textField = new JTextField(40);

    static JLabel blankLabel = new JLabel("           ");

    static JButton sendButton = new JButton("Send");

    static BufferedReader in;

    static PrintWriter out;

    static JLabel nameLabel = new JLabel("         ");

    private Socket soc;



    ChatClient()

    {



        chatWindow.setLayout(new FlowLayout());



        chatWindow.add(nameLabel);

        chatWindow.add(new JScrollPane(chatArea));

        chatWindow.add(blankLabel);

        chatWindow.add(textField);

        chatWindow.add(sendButton);

        chatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        chatWindow.setSize(475, 500);

        chatWindow.setVisible(true);



        textField.setEditable(false);

        chatArea.setEditable(false);



        sendButton.addActionListener(new Listener());

        textField.addActionListener(new Listener());

    }





    void startChat() throws Exception

    {

       String ipAddress = JOptionPane.showInputDialog(

                chatWindow,

                "Enter IP Address:",

                "IP Address Required",

                JOptionPane.PLAIN_MESSAGE);    



       soc = new Socket(ipAddress, 5000);

       in = new BufferedReader(new InputStreamReader(soc.getInputStream()));

       out = new PrintWriter(soc.getOutputStream(), true);

       while (true)

       {

         String str = in.readLine();

           if (str.equals("NAMEREQUIRED"))

           {

           String name = JOptionPane.showInputDialog(

                       chatWindow,

                       "Enter a unique name:",

                       "Name Required!!",

                       JOptionPane.PLAIN_MESSAGE);



               out.println(name);



           }

           else if(str.equals("NAMEALREADYEXISTS"))

           {

           String name = JOptionPane.showInputDialog(

                       chatWindow,

                       "Enter another name:",

                       "Name Already Exits!!",

                       JOptionPane.WARNING_MESSAGE);



               out.println(name);

           }

           else if (str.startsWith("NAMEACCEPTED"))

           {

               textField.setEditable(true);

               nameLabel.setText("You are logged in as: "+str.substring(12));



           }

           else

           {

               chatArea.append(str + "\n");

           }

       }

   }



      public static void main(String[] args) throws Exception {

            // TODO Auto-generated method stub

            ChatClient client = new ChatClient();

            client.startChat();

      }

}

class Listener implements ActionListener

{

      @Override

      public void actionPerformed(ActionEvent e) {

            // TODO Auto-generated method stub

            ChatClient.out.println(ChatClient.textField.getText());

            ChatClient.textField.setText("");

      }



}

服务器:

//ChatServer.java

import java.io.*;

import java.net.*;

import java.util.ArrayList;

public class ChatServer {



      static ArrayList<String> userNames = new ArrayList<String>();

      static ArrayList<PrintWriter> printWriters = new ArrayList<PrintWriter>();

      public static void main(String[] args) throws Exception{

           System.out.println("Waiting for clients..."); 

          @SuppressWarnings("resource")
        ServerSocket ss = new ServerSocket(5000);

           while (true)

           {

             Socket soc = ss.accept();

               System.out.println("Connection established");

             ConversationHandler handler = new ConversationHandler(soc);

             handler.start();

           }



      }

}

class ConversationHandler extends Thread

{

    Socket socket;

    BufferedReader in;

    PrintWriter out;

    String name;

    PrintWriter pw;

    static FileWriter fw;

    static BufferedWriter bw;



   public ConversationHandler(Socket socket) throws IOException {

        this.socket = socket;

        fw = new FileWriter("C:\\Users\\Edoardo Sella\\Desktop\\ChatServer-Logs.txt",true);

        bw = new BufferedWriter(fw);

        pw = new PrintWriter(bw);

    }

   public void run()

   {

        try

        {

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out = new PrintWriter(socket.getOutputStream());

            while (true)

            {

               int _count = 0;

               if(_count > 0)

               {
                    out.println("NAMEALREADYEXISTS");

               }

               else

               {

                    out.println("NAMEREQUIRED");

               }



               name = in.readLine();



               if (name == null)

               {

                   return;

               }



               if (!ChatServer.userNames.contains(name))

               {

                  ChatServer.userNames.add(name);

                  break;

               }

             _count++;

           }



            out.println("NAMEACCEPTED"+name);

            ChatServer.printWriters.add(out);



            while (true)

            {

                String message = in.readLine();



                if (message == null)

                {

                    return;

                }



                pw.println(name + ": " + message);

                for (PrintWriter writer : ChatServer.printWriters) {

                    writer.println(name + ": " + message);

                }

            }



        }

        catch (Exception e)

        {

            System.out.println(e);

        }

   }

}

我真的很困惑为什么客户端没有收到 out.println 命令感谢任何帮助!

【问题讨论】:

  • 代码墙。请去掉所有 Swing 代码和尽可能多的空行。

标签: java sockets server client


【解决方案1】:

这里有多个错误。

最重要的是关于逻辑:在服务器端,你首先监听来自客户端的消息:

name = in.readLine();

这是阻塞。在客户端,你做的完全一样:

String str = in.readLine();

所以,双方都在等待收到的消息,但它永远不会到来。只需添加如下内容:

out.println("hello")

ConversationHandlerrun 方法的开头,您将看到您的消息实际上已被客户端正确接收。

您绝对需要在这里交替,即先选择一个发送消息。

另外,不要忘记刷新输出流,或者更好地使用:

out = new PrintWriter(socket.getOutputStream(), true); 

注意true:它将使打印器自动刷新,即总是立即发送消息(而不是将它们保存在缓存中),即使消息很小。有关冲洗的更多信息,请参阅this question


一些补充说明:

  • 明智地使用空行:在每个语句之间添加一个空行会使代码变得非常大且难以阅读。而是使用空行来分隔逻辑块
  • 在对话处理程序(运行方法)中,您有以下行:

    int _count = 0;
    if (_count > 0)
    

    很容易看出条件永远为真

  • 尽量不要硬编码文件路径(new FileWriter("C:\\Users\\Edoardo Sella\\Desktop\\ChatServer-Logs.txt", true);。首选相对文件路径或至少将它们放在易于查找和更改的全局最终变量中

【讨论】:

  • 非常感谢。问题是打印机只是将消息保存在缓存中而不是发送它们。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
相关资源
最近更新 更多