gpt4 book ai didi

java - 这个简单的服务器-客户端程序不会发送/接收除初始确认之外的数据。为什么?

转载 作者:行者123 更新时间:2023-12-02 11:10:51 26 4
gpt4 key购买 nike

我正在为我的 Comp Sci (Java) 类(class)做一个期末项目,所以我的想法是这是一个简单的服务器-客户端聊天室。当然,我的老师只真正精通 AP 类(class)的各个方面,对制作这样一个程序所需的任何组件知之甚少,所以我或多或少只能靠自己。我一直在使用各种 StackOverflow 帖子和套接字程序的其他示例来对套接字进行逆向工程并弄清楚如何使用它们,但显然,GUI 无法使用检查接收到的消息所需的无限循环进行更新,所以我又回到了谷歌找到更好的方式来监视消息。我想出了尝试使用 propertyChange Listener,这显然是多线程时使用的东西,这是我和我的老师都一无所知的事情列表中添加的另一件事。我找到了一个非常简单且易于理解的(或者我是这么认为的)示例来作为我自己的代码的基础,并运行它。不幸的是,除了服务器和客户端已建立联系的初步确认之外,两个程序之间似乎没有传递任何数据。这是客户端代码:

import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

class ClientRunnable extends newClient implements Runnable {
public Socket sock = new Socket("127.0.0.1", 2702);
public BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
public String receptive = new String();
public String sendToMessage = new String();
public ClientRunnable() throws IOException, InterruptedException {
}
@SuppressWarnings("deprecation")
protected void initUI(ClientRunnable runnable) throws IOException, InterruptedException {
String wrongSizeMSG = "Your username is not the right size. It must be at least 4 characters and \nno larger than 20 characters.";
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.show();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUsername = new JLabel("Please insert your username:");
lblUsername.setBounds(131, 100, 172, 14);
frame.getContentPane().add(lblUsername);
lblUsername.show();
UNInput = new JTextField();
UNInput.setBounds(139, 125, 146, 20);
frame.getContentPane().add(UNInput);
UNInput.setColumns(10);
UNInput.show();
JButton btnGo = new JButton("GO!");
btnGo.setBounds(170, 156, 89, 23);
frame.getContentPane().add(btnGo);
btnGo.show();

JScrollPane scroll = new JScrollPane(msgDisplay);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
frame.getContentPane().add(scroll);
JLabel lblWrongSize = new JLabel(wrongSizeMSG);
lblWrongSize.setForeground(Color.RED);
lblWrongSize.setBounds(10, 172, 414, 50);
lblWrongSize.hide();
frame.getContentPane().add(lblWrongSize);
msgDisplay = new JTextArea();
msgDisplay.setBounds(10, 11, 414, 168);
frame.getContentPane().add(msgDisplay);
msgDisplay.setColumns(10);
msgDisplay.hide();
msgDisplay.setEditable(false);
msgDisplay.setText("");
JLabel lblPrompt = new JLabel("Type:");
lblPrompt.setBounds(10, 190, 46, 14);
frame.getContentPane().add(lblPrompt);
lblPrompt.hide();
txtEditor = new JTextField();
txtEditor.setBounds(10, 215, 414, 35);
frame.getContentPane().add(txtEditor);
txtEditor.setColumns(10);
txtEditor.hide();
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
msgDisplay.setText("Start the chat, type and press Enter key.\n");
pwrite.println("Success");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
username = UNInput.getText();
System.out.println(username);
UNInput.setText("");
if(!(username.toCharArray().length < 4 || username.toCharArray().length > 20)){
btnGo.hide();
lblUsername.hide();
UNInput.hide();
lblWrongSize.hide();
msgDisplay.show();
lblPrompt.show();
txtEditor.show();
} // if
else {
lblWrongSize.show();
}
}
});
txtEditor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
sendMessage = username + "> " + txtEditor.getText() + "\n";
txtEditor.setText("");
pwrite.print(sendMessage);
msgDisplay.setText(msgDisplay.getText() + sendMessage);
pwrite.flush();
}
});
}

private PropertyChangeSupport PCS = new PropertyChangeSupport(this);

public void addPropertyChangeListener(PropertyChangeListener listener) {
PCS.addPropertyChangeListener(listener);
}

@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
} // try-catch
try {
setReceiveRead();
} catch (IOException e) {
e.printStackTrace();
} // try-catch
} // run

public void setReceiveRead() throws IOException {
receptive = receiveRead.readLine();
PCS.firePropertyChange("In", receptive == null, receptive != null);
}

public void propertyChange(PropertyChangeEvent e) {
newClient.msgDisplay.setText(newClient.msgDisplay.getText() + receptive + "\n");
}
} // Runnable

public class newClient{

protected JFrame frame;
protected JTextField UNInput;
public static JTextArea msgDisplay;
protected JTextField txtEditor;
public Socket sock;
public InputStream istream;

public newClient() throws UnknownHostException, IOException {
sock = new Socket("127.0.0.1", 2702);
istream = sock.getInputStream();
}
public BufferedReader receiveRead = new BufferedReader(InputStreamReader(istream));
public String receptive = new String();

public JTextArea getMsgDisplay() {
return msgDisplay;
}

public static void main(String[] args) throws IOException,
InterruptedException {
final ClientRunnable runnable = new ClientRunnable();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
runnable.initUI(runnable);
System.out.println("check there");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
});
new Thread(runnable).start();
System.out.println("Check here");
}
public static String username = new String();
public static String receiveMessage, sendMessage = null;
}

这是服务器代码:

package serverPKGE;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket sersock = new ServerSocket(2702);
System.out.println("Server ready for chatting");

Socket sock = sersock.accept( );
BufferedReader keyRead = new BufferedReader(new
InputStreamReader(System.in));
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);

InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new
InputStreamReader(istream));

String receiveMessage, sendMessage;
while(true) {
if((receiveMessage = receiveRead.readLine()) != null) {
System.out.println(receiveMessage);
} // if
sendMessage = "Server> "
+ "" + receiveMessage;
pwrite.println(sendMessage);
pwrite.flush();
} // while
} // main
} // server

我一次只在一个 GUI 上工作,因此服务器代码更注重数据传输。您能看出客户端无法接收或发送数据的任何明显原因吗?在客户端的早期版本中,存在一种损坏的对话形式,由于某种原因,连接的双方都必须在接收和记录任何一方之前输入一些内容,所以我假设问题出在(至少主要)在客户端代码中。感谢您的帮助。

更新感谢 Scary Wombat 指出我在服务器代码中的错误。我已经更新了代码以反射(reflect)这一点,并且还更改了代码以修复同时打开两个窗口的错误。我仍然不明白代码哪里出了问题。任何其他帮助将不胜感激。再次感谢。

最佳答案

您再次阻塞等待输入

一次

receiveMessage = receiveRead.readLine()

两次

sendMessage = "Server> "
+ "" + keyRead.readLine();

更改为

sendMessage = "Server> "
+ "" + receiveMessage;

关于java - 这个简单的服务器-客户端程序不会发送/接收除初始确认之外的数据。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com