gpt4 book ai didi

java 如何将字符串发送到服务器(jave.net/sockets)

转载 作者:行者123 更新时间:2023-12-01 13:36:16 26 4
gpt4 key购买 nike

我一直致力于构建一个聊天服务器以了解线程和使用套接字。我使用 head First java 作为指导(我仍然对一些事情感到困惑,这就是为什么我可能有这个问题:D),下面的代码就是我所拥有的。

如果您阅读我的代码,您会看到我有客户端通过单击“连接”按钮连接到服务器。当他们这样做时,会弹出一个新的 jframe,询问他们在聊天 session 中的首选名称。当他们输入该内容时,它会保存在客户端代码中的字符串中。我的问题是,如何将此名称传递到服务器,并使其每次客户端发送消息时,他们的名称都显示在消息之前?

感谢您的帮助!!!

(另外,如果有人知道一个可以解释套接字以及套接字/客户端交互如何通过线程发生的好链接,那就太好了!)

服务器代码:

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


public class GameServerOne {
ArrayList clientOutputStreams;
String clientName;
private class ClientThreadHandler implements Runnable {
BufferedReader clientIncomingReader;
Socket socket1;
public ClientThreadHandler(Socket clientSocket2) {
try {
socket1 = clientSocket2;
InputStreamReader clientInputReader = new InputStreamReader(socket1.getInputStream());
clientIncomingReader = new BufferedReader(clientInputReader);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = clientIncomingReader.readLine()) != null) {
tellEveryone(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void setUpServer() {
clientOutputStreams = new ArrayList();
try {
ServerSocket gameSocket = new ServerSocket(5151);
//System.out.println("Server Connected");

while (true) {
Socket clientSocket = gameSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
writer.println("User connected");
writer.flush();
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientThreadHandler(clientSocket));
t.start();


}

} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new GameServerOne().setUpServer();
}


}

客户端代码:

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


public class GameClientOne {
Socket gameSocket;
JFrame inputNameFrame;
JFrame clientFrame;
JTextArea chatArea;
JTextField messageInput;
BufferedReader gameChatReader;
PrintWriter gameChatWriter;
JTextField nameField;
boolean sessionNamePicked = false;
String userSessionName;
BufferedReader gameBufferedReader;



public GameClientOne () {
setUpGUI();
}

public void setUpGUI() {
clientFrame = new JFrame("Game Window");
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel(new BorderLayout());
JPanel centerPanel = new JPanel(new BorderLayout());
chatArea = new JTextArea();
chatArea.setWrapStyleWord(true);
chatArea.setLineWrap(true);
chatArea.setEditable(false);
JScrollPane chatScroller = new JScrollPane(chatArea);
messageInput = new JTextField();
messageInput.addKeyListener(new MessageInputFieldListener());
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
JPanel westPanel = new JPanel(/*new GridLayout(20, 1)*/);
JPanel eastPanel = new JPanel();
JButton connectButton = new JButton("Connect");
connectButton.addActionListener(new ConnectButtonListener());
connectButton.setPreferredSize(new Dimension(100, 28));
JPanel northPanel = new JPanel(new FlowLayout());
JLabel northTitleLabel = new JLabel("Game Screen");
westPanel.add(connectButton);
chatScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) ;
chatScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);



northPanel.add(northTitleLabel);
centerPanel.add(BorderLayout.CENTER, chatScroller);
southPanel.add(BorderLayout.CENTER, messageInput);
southPanel.add(BorderLayout.EAST, sendButton);
mainPanel.add(BorderLayout.SOUTH, southPanel);
mainPanel.add(BorderLayout.CENTER, centerPanel);
mainPanel.add(BorderLayout.WEST, westPanel);
mainPanel.add(BorderLayout.EAST, eastPanel);
mainPanel.add(BorderLayout.NORTH, northPanel);

clientFrame.add(mainPanel);
clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clientFrame.setSize(450, 600);
clientFrame.setVisible(true);
messageInput.requestFocusInWindow();

}
public void setUpInputNameFrame() {
inputNameFrame = new JFrame("Insert Name");
JPanel mainPanel = new JPanel(new BorderLayout());
nameField = new JTextField();
nameField.addKeyListener(new NameFieldListener());
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new SubmitButtonListener());
JLabel inputNameLabel = new JLabel("Please pick a name for the chat session");
JPanel northPanel = new JPanel(new FlowLayout());
JPanel southPanel = new JPanel(new BorderLayout());
northPanel.add(inputNameLabel);
southPanel.add(BorderLayout.CENTER, nameField);
southPanel.add(BorderLayout.EAST, submitButton);
mainPanel.add(BorderLayout.NORTH, northPanel);
mainPanel.add(BorderLayout.SOUTH, southPanel);
inputNameFrame.add(mainPanel);
inputNameFrame.setSize(300, 150);
inputNameFrame.setVisible(true);
nameField.requestFocusInWindow();
}

public void connectToGameServer() {
try {

gameSocket = new Socket("127.0.0.1", 5151);
InputStreamReader gameSocketReader = new InputStreamReader(gameSocket.getInputStream());
gameBufferedReader = new BufferedReader(gameSocketReader);
gameChatWriter = new PrintWriter(gameSocket.getOutputStream());
chatArea.append("Connected with name: " + userSessionName + "\n");
Thread incomingTextThread = new Thread(new IncomingTextReader());
incomingTextThread.start();
//System.out.println("Connected to Game");
} catch (Exception e) {
System.out.println("Could not connect to game...");
e.printStackTrace();
}

}

//ALL LISTENER CLASSES BELOW HERE
//main chat page listeners
private class ConnectButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!sessionNamePicked) {
setUpInputNameFrame();
} else {
chatArea.append("You already connected!\n");
}


}
}
private class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!sessionNamePicked) {
chatArea.append("Please connect first\n");
messageInput.setText("");
messageInput.requestFocusInWindow();
} else {
try {
gameChatWriter.println(messageInput.getText());
gameChatWriter.flush();
} catch (Exception ex2) {
ex2.printStackTrace();
}
//chatArea.append(userSessionName + ": " + messageInput.getText() + "\n");
messageInput.setText("");
messageInput.requestFocusInWindow();
}
}
}
private class MessageInputFieldListener implements KeyListener {
public void keyPressed(KeyEvent e) {

}
public void keyTyped(KeyEvent e) {

}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!sessionNamePicked) {
chatArea.append("Please connect first\n");
messageInput.setText("");
} else {
try {
gameChatWriter.println(messageInput.getText());
gameChatWriter.flush();
} catch (Exception ex2) {
ex2.printStackTrace();
}
//chatArea.append(userSessionName + ": " + messageInput.getText() + "\n");
messageInput.setText("");
}
}
}
}

//pick chat session name listeners: nameField/submitButton
private class NameFieldListener implements KeyListener {
public void keyPressed(KeyEvent e) {

}
public void keyTyped(KeyEvent e) {

}
public void keyReleased(KeyEvent e) {
if (!nameField.getText().isEmpty() && e.getKeyCode() == KeyEvent.VK_ENTER) {
userSessionName = nameField.getText();
sessionNamePicked = true;
connectToGameServer();
inputNameFrame.dispose();
messageInput.requestFocusInWindow();
}

}
}
private class SubmitButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (!nameField.getText().isEmpty()) {
userSessionName = nameField.getText();
sessionNamePicked = true;
connectToGameServer();
inputNameFrame.dispose();
messageInput.requestFocusInWindow();
}
}
}
//Runnable implementation for threads
private class IncomingTextReader implements Runnable {
public void run() {
String incomingMessage;
try {
while ((incomingMessage = gameBufferedReader.readLine()) != null) {
chatArea.append(incomingMessage + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


public static void main(String[] args) {
GameClientOne gameClient = new GameClientOne();
}


}

最佳答案

如果您想发送的不仅仅是一条消息,那么您将需要一个协议(protocol)来决定如何处理您收到的字符串,而不是仅仅将其发送给所有其他客户端。

例如,在客户端发送客户端名称时,您可以编写 NAME:(客户端名称),然后在服务器上,您可以在 : 处拆分字符串,并检查第一部分是否为 NAME,如果是,将客户端名称设置为字符串的其余部分。您应该考虑您可能还想发送哪些其他类型的数据,并设计一个适用于它的协议(protocol)。

以下是如何执行上述操作的示例:

在客户端上,您可以在连接建立后立即添加行 gameChatWriter.write("NAME:"+name) (当然首先创建名称)。然后在服务器上,在收到消息时不调用 tellEveryone(message),而是创建一个名为 processInput 的方法并调用它,该方法可能如下所示:

private void processInput(String message){
String[] commands=message.split(':');
if(commands[0].equals("NAME")){
clientName=commands[1];
}
else{
tellEveryone(message);
}
}

现在你只有一个String clientName,并且你显然需要更多的信息来用于你想要与之交谈的其他客户端,所以我建议将线程处理程序制作成一个单独的类,你可以为其实例化每个客户都可以持有这样的东西。

完成此操作后,您还可以创建一个单独的方法来编写您想要发送到客户端或服务器的其他内容,以及一个在客户端处理输入的方法。希望这会有所帮助。

关于java 如何将字符串发送到服务器(jave.net/sockets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21247244/

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