我正在用Java开发一个简单的聊天程序....我在客户端代码中找不到源问题..我也已经用另一个聊天客户端测试了服务器,并且它正在工作..但没有与我的客户端...聊天程序非常简单....客户端发送字符串,服务器接收该字符串并将其发送回所有客户端,客户端将其显示在传入的TextArea中。
服务器显示它与我的客户端套接字建立了连接...但是当我发送字符串时,它没有接收到它..而且我找不到问题
它正在与其他聊天客户端一起使用。
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class chatbox {
JFrame fr = new JFrame("Chat");
JPanel pnl = new JPanel();
JPanel pnl2 = new JPanel();
JScrollPane scrl;
JTextArea tarea;
JTextField fld;
JLabel lb;
JLabel lbchat;
JButton btn;
Socket socket;
PrintWriter writer;
BufferedReader reader;
btnListener BL = new btnListener();
void guibuilder() {
fr.setSize(400, 400);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setVisible(true);
fld = new JTextField(20);
lb = new JLabel("Message :");
lbchat = new JLabel("Chat Box");
tarea = new JTextArea(400, 500);
tarea.setLineWrap(true);
scrl = new JScrollPane(tarea);
btn = new JButton("Send");
btn.addActionListener(BL);
pnl.add(lb);
pnl.add(fld);
pnl.add(btn);
pnl2.add(lbchat);
pnl2.add(scrl);
fr.getContentPane().add(BorderLayout.SOUTH, pnl);
fr.getContentPane().add(BorderLayout.CENTER, pnl2);
setUpNet();
Thread readerThread = new Thread(new SR());
readerThread.start();
}
void setUpNet() {
try {
socket = new Socket("127.0.0.1", 5000);
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(streamReader);
System.out.println("networking established");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
class btnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
writer.print(fld.getText());
writer.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
fld.setText("");
fld.requestFocus();
}
}//inner class end
class SR implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read" + message);
tarea.append(message + "\n");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}//inner class end
}
public class test {
public static void main(String[] arg) {
chatbox c = new chatbox();
c.guibuilder();
}
}
答案 0 :(得分:0)
信用:user207421
我正在使用PrintWriter流的print()而不是println()。由于服务器正在使用BufferedReader的readlLine(),因此print()无法正常工作。