- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试了解套接字和 ServerSockets 在 Java 中如何工作,因此我尝试做一个聊天服务器,但同时使用线程来处理每个客户端。我认为我需要重新审视我的代码,因为我不知道为什么它不起作用。程序启动,但客户端未连接,并且未创建。我相当确定我的客户类出了问题,但我不确定需要修复什么。任何帮助,即使只是一个有用资源的链接,我们都将非常感激。谢谢。
服务器代码
package chatbox.server;
import static java.lang.System.out;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Server {
public final static int DEFAULT_PORT = 5000;
private ServerSocket socket;
private ArrayList<Socket> clients;
public Server(int port) throws IOException {
System.out.println("Server is now online");
System.out.println("port: " + port);
this.socket = new ServerSocket(port);
System.out.println("Listening socket established");
System.out.println("Waiting for connections...");
this.clients = new ArrayList<Socket>();
while (true) {
try {
final Socket connection = this.socket.accept();
this.clients.add(connection);
Runnable incomingMsg = new Runnable() {
private InputStream inputStream = connection.getInputStream();
private InputStreamReader reader = new InputStreamReader(
inputStream);
private Scanner scanner = new Scanner(reader);
@Override
public void run() {
while (true) {
if (scanner.hasNextLine()) {
String msg = scanner.nextLine();
System.out.println("Handling message: \"" + msg
+ "\"");
notifyAllConnections(msg);
}
}
}
};
Thread thread = new Thread(incomingMsg);
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable exc) {
try {
connection.close();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
clients.remove(connection);
System.out.println("Removed connection");
}
}
});
thread.start();
System.out.println("Added new connection");
} catch (IOException exc) {
System.out
.println("Error occurred.");
}
}
}
protected void notifyAllConnections(String msg) {
for (Socket sock : this.clents) {
try {
OutputStream out = sock.getOutputStream();
PrintStream printer = new PrintStream(out);
printer.println(msg);
printer.flush();
} catch (IOException exc) {
System.out.println("Message was not fully broadcast");
}
}
}
public static void main(String[] args) {
try {
Server server = new Server(
Server.DEFAULT_PORT);
} catch (IOException exc) {
System.out
.println("Could not create the server socket.");
exc.printStackTrace();
String servername = "localhost";
try {
new Client(servername, 5000);
} catch (Exception ex) {
out.println("Error" + ex.getMessage());
}
}
}
}
客户端代码
package chatbox.client
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.System.out;
public class Client extends JFrame {
private PrintWriter pw;
private Scanner scanner;
private JPanel chatAndSend;
private JTextArea chatWindow;
private JScrollPane mainScroll;
private JTextArea chatText;
private JScrollPane miniScroll;
private JButton send;
private Socket client;
public Client(String servername, int port) throws Exception {
this.client = new Socket(servername, port);
this.scanner = new Scanner(new InputStreamReader(
this.client.getInputStream()));
this.pw = new PrintWriter(this.client.getOutputStream());
makeGUI();
new MessagesThread().start();
}
public void makeGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
this.chatWindow = new JTextArea(10, 20);
this.chatWindow.setEditable(false);
this.chatWindow.setLineWrap(true);
this.mainScroll = new JScrollPane(chatWindow,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(this.mainScroll, BorderLayout.NORTH);
this.chatAndSend = new JPanel();
this.chatAndSend.setLayout(new FlowLayout());
this.chatText = new JTextArea(1, 1);
this.chatText.setLineWrap(true);
this.miniScroll = new JScrollPane(chatText,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.chatAndSend.add(this.miniScroll);
this.send = new JButton();
this.send.setText("SEND");
this.send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pw.println(chatText.getText());
pw.flush();
}
});
this.chatAndSend.add(this.send);
this.add(this.chatAndSend, BorderLayout.SOUTH);
this.setVisible(true);
this.pack();
}
class MessagesThread extends Thread {
public void run() {
String line;
try {
while (true) {
line = scanner.nextLine();
chatWindow.append(line + "\n");
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
}
}
最佳答案
while (scanner.hasNextLine()) {
编辑
我已经查看并运行了您的新代码。您是否看到您正在尝试在 catch block 中创建一个从未被调用的新客户端?
最重要的是——运行代码时使用调试器来查看代码正在做什么或没有做什么。还添加 println 语句(更多)。如果您这样做,您会发现 Client 的构造函数从未被调用,并且会知道查看您尝试调用它的代码以了解原因。
关于java - Sockets 和 ServerSockets 服务器/客户端 GUI 聊天程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20296628/
在服务器端,我使用这段代码: ServerSocket server = new ServerSocket(1234); Socket server_socket = server.accept();
假设A是服务器,B是客户端。 B 创建一个到服务器 A 的套接字 b 并 ServerSocket.accept() 创建一个相应的套接字 a 对于客户端 B 现在,如果服务器 A 关闭了 a 但客户
我想在单独的线程中运行Python serversocket 类。为此,我修改了此代码以支持 python 线程: 原始文件 import SocketServer class MyTCPHandle
我正在使用一些 java 创建一个小客户端来监控网络。对于网络上的每个节点,我运行一个客户端,但也运行一个 ServerSocket 来监听传入的连接。我写的代码似乎卡在了 ServerSocket.
虽然 ServerSocket 类被设计为一般监听传入连接,但我可以只使用 Socket 对象来代替并在 java 中检索传入数据吗?如果是,那么我是否需要采取任何额外的预防措施? 编辑:感谢您的回答
我在Java项目的类之一中有一个ServerSocket。该套接字接收一些导致新操作的命令。例如: deleteAllFromDB ->删除数据库上的所有条目。 sendMsgToX ->创建发送到X
我用java写了一个服务器,这里是代码: public mainClass() { try { ss = new ServerSocket(8080);
我目前正在参与学校的一个项目,我们正在构建一个在 Android 手机上使用的通信系统。为此,我们将使用一个向所有客户端打开套接字的服务器,使它们进行通信。 我以前做过几个聊天应用程序,没有任何套接字
我有这两个类 Client.java 和 Server.java,每个类都包含一个 main 方法。想法非常简单,其中的代码也非常相似。我试图实现的目标是打开一个使用 ServerSocket 监听特
这可能是一个愚蠢的问题,但就是这样。我正在编写这个聊天程序,其中有一个服务器和可以连接到它的客户端。我想在程序中实现私有(private)消息传递,但我不知道如何让客户端直接相互连接。对于服务器,我使
ServerSocket 与多个客户端一起使用,我们可能为每个客户端附加单独的线程来工作,但问题是连接工作正常并接受所有客户端,但仅服务最后一个连接。所以这不是问题,或者这是正常现象。 服务器代码:
我是套接字编程的新手,我只是尝试一些东西。我想做的是让客户端读取文本文件,将该文件中的行保存在 ArrayList 中,然后将这些行发送到服务器。这是我的代码。连接成功建立,但是当服务器尝试从他的Bu
我有以下代码片段: if (servsock == null) { System.out.println("HELLO1!"); servsock = new ServerSocket
我正在查看serversocket API,它说允许的最大连接数是50。我尝试测试它.. public class ClientSocketTest { public static void
我试图制作一个小聊天程序,但它真的不想工作。我的服务器和客户端基本相同:它们创建一个新的套接字和一个新的聊天(GUI)。有人可以帮我找出我犯的错误吗? 服务器代码: import java.io.In
我尝试使用蓝牙将图像从一个设备发送到其他设备。为此,我采用 Android 蓝牙聊天应用程序源代码,当我发送字符串时它工作正常。但是如果我将图像作为字节数组发送,则 while 循环不会中断或从输入流
我目前正在为我的大学开发一款 TicTacToe 多线程网络游戏,但遇到了一个恼人的问题。 我希望我的服务器每次接受 2 个连接,然后等待其他 2 个连接等。 问题是,在我的代码中,如果客户端连接到服
我正在构建一个简单的服务器应用程序,我可以在本地网络中连接到它。但我无法通过互联网连接。 这是我的服务器代码: ServerSocket server; try { server = new
我有以下构造: try { serverSocket = new ServerSocket(port); } catch (Exception e) { throw new Runti
我一直在尝试在我创建的应用程序中开发一个嵌入式网络服务器。本质上,我们有创建一个简单网络服务器(使用 ServerSocket)的主进程,然后主进程(理论上)将处理它的业务。 Main(){
我是一名优秀的程序员,十分优秀!