简体   繁体   English

writeBytes对服务器/客户端程序不起作用

[英]writeBytes not working for Server/Client Program

I am trying to understand this tutorial code, http://www.cise.ufl.edu/~amyles/tutorials/tcpchat/ , the TCPChat.java. 我试图理解本教程代码,即http://www.cise.ufl.edu/~amyles/tutorials/tcpchat/(TCPChat.java )。

Here is my program, 这是我的程序

import java.lang.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

public class GuessMyNumber{

JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JLabel hostL = new JLabel("Host IP:");
static JTextField hostTF = new JTextField("localhost");
JButton hostBtn = new JButton("Host");
JButton connectBtn = new JButton("Connect");
JButton disconnectBtn = new JButton("Disconnect");
static JTextField chatText = new JTextField();
JButton sendBtn = new JButton("Send");

static int status = 0; // 1:Disconnected, 2:Disconnecting, 3:Begin Connect, 4:Connected
static boolean isHost = true;
static int port = 1234;
public static ServerSocket hostServer = null;
public static Socket socket = null;
public final static String END_CHAT_SESSION =
  new Character((char)0).toString();
  static DataInputStream dis = null;
  static DataOutputStream dos = null;
  static String toSend = "";
  static String s = "";

GuessMyNumber(){
    frame.setTitle("Guess My Number");
    frame.setSize(500,500);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    mainPanel.setLayout(null);

    hostL.setBounds(10,10,50,20);
    hostTF.setBounds(60,10,140,20);
    hostBtn.setBounds(210,10,60,20);
    connectBtn.setBounds(280,10,90,20);
    disconnectBtn.setBounds(380,10,100,20);
    disconnectBtn.setEnabled(false);
    chatText.setBounds(60,40,140,20);
    sendBtn.setBounds(210,40,60,20);
    mainPanel.add(hostL);
    mainPanel.add(hostTF);
    mainPanel.add(hostBtn);
    mainPanel.add(connectBtn);
    mainPanel.add(disconnectBtn);
    mainPanel.add(chatText);
    mainPanel.add(sendBtn);

    hostBtn.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        beginHost();
                    }
                }
            );

    connectBtn.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        beginConnect();
                    }
                }
            );

    disconnectBtn.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        disConnect();
                    }
                }
            );

    sendBtn.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        toSend = chatText.getText();
                    }
                }
            );

    frame.add(mainPanel);
    frame.setVisible(true);
}

public static void main(String[] args){
    GuessMyNumber gmn = new GuessMyNumber();
    while (true) {
     try { // Poll every ~10 ms
        Thread.sleep(10);
     }
     catch (InterruptedException e) {}

     if(status == 3){
        try {
           if (isHost) {
              hostServer = new ServerSocket(port);
              socket = hostServer.accept();
           }
           else {
              socket = new Socket(hostTF.getText(), port);
           }
            dis = new DataInputStream(socket.getInputStream());
            dos = new DataOutputStream(socket.getOutputStream());
            status = 4;
            System.out.println("COnnected");
        }
        catch (IOException e) {
           e.printStackTrace();
        }
     }else
     if(status == 4){
        System.out.println("Ready to Chat");
        try {
           System.out.println(toSend.length());
           if (toSend.length() != 0) {
              dos.writeBytes(toSend);
              toSend="";
              chatText.setText("");
           }

           if((s = dis.readLine()) != null){
              if ((s != null) &&  (s.length() != 0)) {
                 if (s.equals(END_CHAT_SESSION)) {
                 }

                 else {

                    System.out.println("loL");
                 }
              }
           }


        }catch (Exception e) {

           e.printStackTrace();
        }
     }else
     if(status == 2){
        System.out.println("Discon na!");
        try {

        }
        catch (Exception e) {

           e.printStackTrace();
        }
     }
  }
}

public void beginConnect(){
    status = 3;
    isHost = false;
    hostTF.setEditable(false);
    hostBtn.setEnabled(false);
    connectBtn.setEnabled(false);
    disconnectBtn.setEnabled(true);
}

public void disConnect(){
    status = 2;
    hostTF.setEditable(true);
    hostBtn.setEnabled(true);
    connectBtn.setEnabled(true);
    disconnectBtn.setEnabled(false);
}

public void beginHost(){
    status = 3;
    isHost = true;
    hostTF.setEditable(false);
    hostBtn.setEnabled(false);
    connectBtn.setEnabled(false);
    disconnectBtn.setEnabled(true);
}

}

Running my program, it prints out "Connected", "ready to Chat", and "0".. So the Server and The Client are connected. 运行我的程序,它会打印出“已连接”,“准备聊天”和“ 0”。。因此服务器和客户端已连接。 If server or the client try to send a message, it is not working. 如果服务器或客户端尝试发送消息,则该消息不起作用。 Can anyone help me to solve this problem? 谁能帮我解决这个问题?

In the tutorial code, they used BufferReader , but I used DataInputStream . 在教程代码中,他们使用了BufferReader ,但我使用了DataInputStream In bufferReader , they can use .ready() , but for DataInputStream it doesn't have that method. bufferReader ,他们可以使用.ready() ,但对于DataInputStream则没有该方法。 I think it is one of a factors causing this problem. 我认为这是导致此问题的因素之一。

instead of repeatedly pooling for things in your while loop yo should instead put the relevant code in or be called from the action listeners. 而不是在while循环中重复池中的东西,而应将相关代码放入动作侦听器中或从动作侦听器中调用它们。

So instead of just 所以不只是

        sendBtn.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    toSend = chatText.getText();
                }
            }
        );

You should also put the code that actually writes the text across the network. 您还应该放置实际在网络上写入文本的代码。 If it takes too long to write the text and you find its locking up the gui you can instead use a SwingWorker to have it run in the background. 如果编写文本花费的时间太长,而您发现它锁定了gui,则可以使用SwingWorker在后台运行它。

System.out.println(toSend.length());
           if (toSend.length() != 0) {
              dos.writeBytes(toSend);
              toSend="";
              chatText.setText("");

Instead of writing dos.writeBytes(toSend) you may write dos.writeBytes(toSend+'\\n'). 代替编写dos.writeBytes(toSend),您可以编写dos.writeBytes(toSend +'\\ n')。 It should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM