- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在用 Java 使用如下所示的 GUI 编写聊天程序
这个想法是在一台计算机上启动服务器,在另一台(或多台)计算机上启动客户端(我目前只是在同一台计算机上运行两者)。服务器启动后,客户端输入主机号和端口号并点击连接。到目前为止,所有这些都在起作用。连接后,用户或服务器都可以在文本字段中键入并点击发送,消息可以发送到服务器,服务器将消息发送到所有客户端。
我的问题是:如何将文本从客户端发送到服务器,反之亦然?
我无法理解它是如何工作的。服务器处于 while 循环并等待更多连接(所有这些都有效),所以我不知道它如何接受文本然后将其推回。
这是整个程序,您可以编译它并查看我遇到的问题:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.io.PrintWriter;
import java.util.Scanner;
public class Chat extends Frame implements Runnable, WindowListener, ActionListener, ItemListener
{
int port = 44004;
String host = "127.0.0.1";
//GUI objects
TextField ipAddressField = new TextField();
TextField portField = new TextField(""+port);
TextField hostField = new TextField(host);
TextField inputBox = new TextField();
static TextArea conversationBox = new TextArea();
Button startServerButton = new Button("Start Server");
Button sendButton = new Button("Send");
Button changeHost = new Button("Change Host");
Button changePort = new Button("Change Port");
Button connectButton = new Button("Connect");
Button disconnectButton = new Button("Disconnect");
Label hostLabel = new Label("Host:");
Label portLabel = new Label("Port:");
MenuBar mb = new MenuBar();
Menu colorMenu = new Menu("Color");
CheckboxMenuItem redItem = new CheckboxMenuItem("Red");
CheckboxMenuItem blueItem = new CheckboxMenuItem("Blue");
CheckboxMenuItem orangeItem = new CheckboxMenuItem("Orange");
CheckboxMenuItem blackItem = new CheckboxMenuItem("Black");
//runtime variables
Color color = Color.red;
volatile boolean kill = false;
volatile boolean isServer = false;
volatile boolean isClient = false;
String connections[];
//messaging variables
String message;
Scanner in;
PrintWriter out;
public static void main(String [] args)
{
new Chat();
}
ServerSocket server;
Socket s;
//gui components
protected Chat()
{
double[] colWeight = {1,1,1,1,1,1};
double[] rowWeight = {5,1,1,1,1};
int[] colWidth = {1,1,1,1,1,1};
int[] rowHeight = {5,1,1,1,1};
GridBagConstraints c = new GridBagConstraints();
GridBagLayout gbl = new GridBagLayout();
gbl.rowHeights = rowHeight;
gbl.columnWidths = colWidth;
gbl.columnWeights = colWeight;
gbl.rowWeights = rowWeight;
setBounds(100,100,400,600);
setLayout(gbl);
//add conversation box
this.conversationBox.setSize(400, 400);
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 5;
c.gridheight = 5;
c.fill = 1;
c.gridx = 0;
c.gridy = 0;
gbl.setConstraints(this.conversationBox, c);
//input text box
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 4;
c.gridheight = 1;
c.fill = 1;
c.gridx = 0;
c.gridy = 5;
gbl.setConstraints(this.inputBox, c);
//send button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 5;
gbl.setConstraints(this.sendButton, c);
//host label
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 0;
c.gridy = 6;
gbl.setConstraints(this.hostLabel, c);
//host input
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = 1;
c.gridx = 1;
c.gridy = 6;
gbl.setConstraints(this.hostField, c);
//change host button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 3;
c.gridy = 6;
gbl.setConstraints(this.changeHost, c);
//start server button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 6;
gbl.setConstraints(this.startServerButton, c);
//row
//port label
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 0;
c.gridy = 7;
gbl.setConstraints(this.portLabel, c);
//port input
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = 1;
c.gridx = 1;
c.gridy = 7;
gbl.setConstraints(this.portField, c);
//change port button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 3;
c.gridy = 7;
gbl.setConstraints(this.changePort, c);
//connect button
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 7;
gbl.setConstraints(this.connectButton, c);
//disconnect button, shunned in the corner
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = 1;
c.gridx = 4;
c.gridy = 8;
gbl.setConstraints(this.disconnectButton, c);
mb.add(colorMenu);
colorMenu.add(redItem);
colorMenu.add(blueItem);
colorMenu.add(orangeItem);
colorMenu.add(blackItem);
add(this.conversationBox);
add(this.inputBox);
add(this.sendButton);
add(this.hostLabel);
add(this.hostField);
add(this.changeHost);
add(this.startServerButton);
add(this.portLabel);
add(this.portField);
add(this.changePort);
add(this.connectButton);
add(this.disconnectButton);
inputBox.addActionListener(this);
sendButton.addActionListener(this);
changeHost.addActionListener(this);
changePort.addActionListener(this);
startServerButton.addActionListener(this);
connectButton.addActionListener(this);
disconnectButton.addActionListener(this);
hostField.addActionListener(this);
portField.addActionListener(this);
redItem.addItemListener(this);
blueItem.addItemListener(this);
orangeItem.addItemListener(this);
blackItem.addItemListener(this);
setMenuBar(mb);
addWindowListener(this);
setResizable(true);
pack();
setVisible(true);
new Thread(this).start();
}
public void run()
{
conversationBox.appendText("Session Start.\n");
inputBox.requestFocus();
while (!kill)
{
if (isServer)
{
conversationBox.appendText("Server starting on port " + port + "\n");
conversationBox.appendText("Waiting for clients...\n");
startServer();
}
if (isClient)
{
conversationBox.appendText("Starting connection to host " + host + " on port " + port + "\n");
startClient();
}
}
}
public void startClient()
{
try
{
Socket c = new Socket(host, port);
in = new Scanner(c.getInputStream());
out = new PrintWriter(c.getOutputStream());
while (true)
{
if (in.hasNext())
{
Chat.conversationBox.appendText("You Said: " + message);
out.println("Client Said: " + message);
out.flush();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void startServer()
{
try
{
server = new ServerSocket(port);
while (true)
{
s = server.accept();
conversationBox.appendText("Client connected from " + s.getLocalAddress().getHostName() + "\n");
}
}
catch (Exception e)
{
conversationBox.appendText("An error occurred.\n");
e.printStackTrace();
isServer = false;
reEnableAll();
}
}
public void actionPerformed(ActionEvent e) throws NumberFormatException
{
Object o = e.getSource();
if (o == sendButton || o == inputBox)
{
if(inputBox.getText() != "")
{
out.println(inputBox.getText());
inputBox.setText("");
}
}
if (o == changeHost || o == hostField)
{
if (hostField.getText() != "" && hostField.getText() != host)
{
host = hostField.getText();
conversationBox.appendText("Host changed to " + host + "\n");
}
}
if (o == changePort || o == portField)
{
if (portField.getText() != "" && Integer.valueOf(portField.getText()) != port)
{
try
{
port = Integer.valueOf(portField.getText());
conversationBox.appendText("Port changed to " + port + "\n");
}
catch(NumberFormatException up)
{
throw up; //blargh enter a real value
}
}
}
if (o == startServerButton)
{
isServer = true;
isClient = false;
startServerButton.enable(false);
connectButton.enable(false);
changeHost.enable(false);
changePort.enable(false);
hostField.enable(false);
portField.enable(false);
}
if (o == connectButton)
{
isServer = false;
isClient = true;
startServerButton.enable(false);
}
inputBox.requestFocus();
}
public void reEnableAll()
{
startServerButton.enable(true);
connectButton.enable(true);
changeHost.enable(true);
changePort.enable(true);
hostField.enable(true);
portField.enable(true);
}
public void windowClosing(WindowEvent e)
{
removeWindowListener(this);
inputBox.removeActionListener(this);
sendButton.removeActionListener(this);
changeHost.removeActionListener(this);
changePort.removeActionListener(this);
startServerButton.removeActionListener(this);
connectButton.removeActionListener(this);
disconnectButton.removeActionListener(this);
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void itemStateChanged(ItemEvent e)
{
Object o = e.getSource();
if (o == redItem)
{
redItem.setState(true);
blueItem.setState(false);
orangeItem.setState(false);
blackItem.setState(false);
color = Color.red;
}
if (o == blueItem)
{
redItem.setState(false);
blueItem.setState(true);
orangeItem.setState(false);
blackItem.setState(false);
color = Color.red;
}
if (o == orangeItem)
{
redItem.setState(false);
blueItem.setState(false);
orangeItem.setState(true);
blackItem.setState(false);
color = Color.red;
}
if (o == blackItem)
{
redItem.setState(false);
blueItem.setState(false);
orangeItem.setState(false);
blackItem.setState(true);
color = Color.red;
}
}
}
最佳答案
我测试了你的代码,我发现在你的 startServer() 函数中,你没有创建 OutputStream 和 InputStream
像这样修改您的startClient
函数:(创建两个全局变量:BufferedWriter bw
和BufferedReader br
,因为我们需要它在您的actionPerformed
函数)
BufferedWriter bw = null;
BufferedReader br = null;
public void startClient()
{
try
{
Socket c = new Socket(host, port);
bw = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
br = new BufferedReader(new InputStreamReader(c.getInputStream()));
char buffer[] = new char[1024];
while (br.read(buffer) > 0)
{
Chat.conversationBox.appendText("You Said: " + new String(buffer));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
像这样修改您的 startServer
函数:
public void startServer()
{
try
{
server = new ServerSocket(port);
while (true)
{
s = server.accept();
s.getInputStream();
conversationBox.appendText("Client connected from " + s.getLocalAddress().getHostName() + "\n");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
char buffer[] = new char[1024];
conversationBox.appendText("Reading....");
while(br.read(buffer) > 0)
{
conversationBox.appendText("Client Say : " + new String(buffer));
bw.write(buffer);
bw.flush();
}
conversationBox.appendText("Reading Done....");
}
}
catch (Exception e)
{
conversationBox.appendText("An error occurred.\n");
e.printStackTrace();
isServer = false;
reEnableAll();
}
}
并且在您的actionPerformed
函数中,请修改以下代码:
if (o == sendButton || o == inputBox)
{
if (inputBox == null)
{
System.out.println("NULL");
}
if(inputBox.getText() != "")
{
//out.println(inputBox.getText());
//out.flush();
try
{
bw.write(inputBox.getText());
bw.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
inputBox.setText("");
}
}
关于java - 如何让我的 java 聊天客户端和服务器从文本字段交换消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675602/
我想在一些计算机之间建立点对点连接,这样用户就可以在没有外部服务器的情况下聊天和交换文件。我的第一个想法如下: 我在服务器上创建了一个中央 ServerSocket,所有应用程序都可以连接到该服务器。
我正在 Unity 中构建多人游戏。为此,我必须将一些值从客户端发送到两个或多个通过服务器连接的客户端。我想将其构建为服务器真实游戏。客户端将使用 Android,他们的数据将通过服务器同步(可能是一
练习 C 网络编程:我正在编写一个简单的 TCP 客户端-服务器应用程序,它应该将消息(在每个客户端的单独线程中)作为字符串从服务器发送到客户端并在客户端(稍后将成为控制台商店应用程序)。我首先发送消
我使用证书身份验证设置了 AWS Client VPN。我正在为客户端-客户端访问系统进行设置,基本上如 this AWS scenario/example 中所述.一切正常,如果我知道他们的 IP
我正在开发一个小型客户端1/客户端2、服务器(线程)TCP 游戏。在尝试处理延迟问题时,我意识到我的 transmitState() 中存在缺陷。它强制将不必要的信息传递到通讯流中,从而造成迟缓,将汽
来自文档:Configurable token lifetimes in Azure Active Directory (Public Preview) 它提到“ secret 客户端”,刷新 tok
Apollo 客户端开发工具无法连接到我的应用程序。我已在 ApolloClient 构造函数中将 connectToDevTools 传递为 true,但没有任何 react 。我也试过this p
我想在 Pod 内使用 Fabric8 kubernetes 客户端 (java)。如何获取部署集群的 kubernetes 客户端? 我可以使用该集群的 kubeconfig 文件获取任何集群的配置
我正在阅读 the security issue with Log4j我了解此产品受此漏洞影响。但是 Oracle 客户端 11.2 和 12 是否受此问题影响? 我找不到这些产品是否使用任何 Log
Eureka 服务器设置 pom.xml 1.8 Hoxton.SR1 org.springframework.cloud spring
我有一个点对点(客户端/服务器)设置(通过本地 LAN),它使用 Netty,一个 Java 网络框架。我使用原始 TCP/IP(例如,没有 HTTP)进行通信和传输。现在,根据要求,我们希望转向 T
上一篇已经实现了ModbusTcp服务器和8个主要的功能码,只是还没有实现错误处理功能。 但是在测试客户端时却发现了上一篇的一个错误,那就是写数据成功,服务器不需要响应。 接下来要做的就是实现Modb
有没有办法将二维十六进制代码数组转换为 png 图像? 数组看起来像这样(只是更大) [ [ '#FF0000', '#00FF00' ], [ '#0000FF'
我是套接字编程的新手。每次我运行客户端程序时,它都会说“无法连接到服务器”。谁能告诉我我在哪里犯了错误。任何帮助将不胜感激。 这是client.c #include #include #inclu
我们在UNIX环境下制作了简单的client.c和server.c程序。我们使用它来传输一个简单的文本文件,首先打开它,然后读取它并使用 open、read 和 send 系统调用发送;在客户端,我接
当我的程序来自 my previous question正在响应客户端,它应该发送加密消息。 当客户端连接时,它会发送一条类似“YourMessage”的消息。现在我想做的是,当客户端连接时,应该以某
我正在使用 C 和 putty 编写客户端/服务器程序。两个 c 文件位于同一系统上。 我目前在向客户端写回其正在使用的框架以及打印我的框架时遇到问题。它打印出 3 0 9 8,但随后开始打印 134
我正在使用 C 中的 select() 制作一个模拟快餐或其他任何东西的客户端服务器。 我有客户随机点 1-5 种“食物”。服务器每 30 秒决定一次。所有客户最喜欢的食物是什么?他为那些客户提供服务
对于单机游戏,基本的游戏循环是(来源:维基百科) while( user doesn't exit ) check for user input run AI move enemies
1、CentOS安装TortoiseSVN 复制代码 代码如下: yum install -y subversion 2、SVN客户端命令
我是一名优秀的程序员,十分优秀!