我正在尝试在两个客户端之间构建一个小型聊天服务器。我正在为每个客户使用Threads。
我能够正面和背面发送一条消息,但随后一切都变成了sh * t。
以下是代码:
服务器类
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private static Socket connection = null;
private String message;
private String message2;
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
int counter = 0;
//constructor
public Server(){
super("Server");
userText = new JTextField();
userText.setEditable(false);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);
}
//set up and run the server
public void startRunning(){
try{
server = new ServerSocket(6789, 100);
while(true){
try{
waitForConnection();
// setupStreams();
// whileChatting();
}catch(EOFException eofException){
showMessage("\n Server ended the connection! ");
}finally{
closeConnection();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException{
while (true) {
try {
connection = server.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(connection, threads)).start();
showMessage("heehehehe");
counter++;
break;
}
}
if (i == maxClientsCount) {
connection.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//close streams and sockets after you are done chatting
private void closeConnection(){
showMessage("\n Closing connections... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
//let the user type stuff into their box
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
class clientThread extends Thread {
private String clientName = null;
private ObjectInputStream is = null;
private ObjectOutputStream os = null;
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
}
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
try {
is = new ObjectInputStream(clientSocket.getInputStream());
os = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
String message = (String)is.readObject();
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null ) {
threads[i].os.writeObject(message);
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
}
}
}
} catch (IOException | ClassNotFoundException e) {
}
}
}
客户端类:
package Client;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class Client extends JFrame implements Runnable{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
private JButton button = new JButton("Image");
//Constructor
public Client(String host){
super("PHONE");
this.serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
chatWindow.setSize(new Dimension(100,200));
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setSize(300,150);
setVisible(true);
}
//connect to server
public void startRunning(){
try {
connectToServer();
setupStream();
// whileChatting();
receiveMessage();
} catch (EOFException eofException) {
showMessage("\n Client terminated connection");
// TODO: handle exception
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//connect to a server
private void connectToServer() throws IOException{
showMessage("Attempting connection ...");
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage("Connected to" + connection.getInetAddress().getHostAddress());
}
//setup streams to send and receive messages;
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
input = new ObjectInputStream(connection.getInputStream());
}
private void receiveMessage() throws IOException{
ableToType(true);
while(true) {
try {
message = (String)input.readObject();
showMessage("\n" + message);
} catch (ClassNotFoundException classNotFoundException) {
showMessage("\n Idk wtf dude!!");
// TODO: handle exception
}
}
}
private void sendMessage(String message){
try {
output.writeObject(": " + message);
output.flush();
showMessage("\nYou: " + message);
} catch (IOException e) {
chatWindow.append("\n Something went wrong");
// TODO: handle exception
}
}
//change / update chatWndows
private void showMessage(final String msg){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(msg);
}
}
);
}
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable() {
public void run(){
userText.setEditable(tof);
}
}
);
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
从数组中删除'this'条目的for循环不应该在读/写循环中。只有在客户端断开连接时才会删除该条目,即。发生错误/异常时检查所有服务器和客户端代码是否存在严重的结构错误,并使用调试器跟踪代码执行,而不是在此处不断编辑更正