简体   繁体   中英

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.

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. 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 . In bufferReader , they can use .ready() , but for DataInputStream it doesn't have that method. 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.

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.

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'). It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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