writeBytes不适用于服务器/客户端程序

时间:2015-03-19 14:11:47

标签: java sockets client server

我正在尝试理解这个教程代码http://www.cise.ufl.edu/~amyles/tutorials/tcpchat/,TCPChat.java。

这是我的程序,

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

}

运行我的程序,打印出“已连接”,“准备聊天”和“0”..因此服务器和客户端已连接。如果服务器或客户端尝试发送消息,则它无法正常工作。任何人都可以帮我解决这个问题吗?

在教程代码中,他们使用了BufferReader,但我使用了DataInputStream。在bufferReader中,他们可以使用.ready(),但对于DataInputStream,它没有该方法。我认为这是造成这个问题的因素之一。

2 个答案:

答案 0 :(得分:0)

而不是在while循环中反复汇集内容,而应该将相关代码放入或从动作侦听器中调用。

所以而不仅仅是

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

您还应该将实际写入文本的代码放在网络上。如果编写文本需要很长时间而你发现它锁定了gui,你可以使用SwingWorker让它在后台运行。

答案 1 :(得分:0)

{{1}}

您可以编写dos.writeBytes(toSend +'\ n'),而不是编写dos.writeBytes(toSend)。它应该工作。