Java客户端和服务器已连接但未通信

时间:2017-02-19 18:46:26

标签: java sockets server client

所以我试图创建一个客户端 - 服务器聊天应用程序,并且我已经编写了该程序。客户端和服务器通过localhost上的公共端口(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命令,感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

这里有多个错误。

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

name = in.readLine();

阻止。在客户端,您完全一样:

String str = in.readLine();

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

out.println("hello")

run ConversationHandler方法的开头,您将看到客户实际上正确接收了您的消息。

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

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

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

请注意true:它会使printwriter autoflush ,即使邮件很小,也会立即发送邮件(与将邮件保留在缓存中)。有关刷新的详细信息,请参阅https://en.wikipedia.org/wiki/Wilks_Coefficient

其他一些评论:

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

    int _count = 0;
    if (_count > 0)
    

    很容易看出情况总是如此

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