服务器/客户端程序在线程启动后停止工作 [英] Server / client program stops working after Thread starts

查看:37
本文介绍了服务器/客户端程序在线程启动后停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的 5 天里,我一直试图找出我的程序不起作用的原因,我在这里提出了无数问题,得到了很好的回应,现在看来我已经找到了问题所在.

I have over the past 5 days tried to find out why my program does not work i have been asking countless questions in here with good responses and it seems that i have now found the problem.

背景故事:

我有一个聊天程序,它分为客户端和服务器两个独立的应用程序.这个想法是制作一个聊天程序,让客户端有一个包含图片、一些标签和一些文本区域的 GUI.

I have a chat program that is devided into two seperate applications a Client and Server. The idea is to make a chat program so ever client has a GUI that contains a picture and some labels and a few textAreas.

每当客户端启动 Gui 节目并且用户能够点击按钮连接以尝试与服务器连接时,以下就是我的程序中直接发生的情况,程序的这一部分工作正常:

Whenever the client starts up the Gui show and the user is able to hit the button connect to try and connect with the server the follwing this is directly what happens in my program and this part of the program works fine:

** 正在按下连接按钮**客户端发送到服务器:1服务器发送给客户端:1服务器发送给客户端:1客户端发送到服务器:Marc(聊天者用户名)

** The connect button is being pushed** Client sends to server: 1 Server sends to client: 1 Server sends to client: 1 Client sends to server: Marc (The chat persons username)

客户端发送到服务器:5服务器发送给客户端:1服务器发送给客户端:1服务器发送给客户端:Marc

Client sends to server: 5 Server sends to client: 1 server sends to client: 1 Server sends to client: Marc

客户端发送到服务器:8服务器发送给客户端:8

Client sends to server: 8 Server sends to client: 8

现在一切都崩溃了,因为现在我的 Gui 中的线程开始了.从这里开始,程序显然无法从这里接收来自服务器的消息.即使服务器收到消息.这怎么可能?

And now all hell breaks loose because now the Thread in my Gui Starts. and from here on the program is apprently unable to recive messages from the server from here on. even though the server recives the messages. How can this be?

为了不发布大量代码,如果您需要更多代码,我将发布我程序的重要部分,很高兴更新帖子

in order to not post loads of code i am going to post the important parts of my program if you need more code il be glad to update the post

线程(在 simpleController(控制 GUI 的控制器)中)

public void run(){ 
    System.out.println("Thread started");
    System.out.println(client.getSocket().isConnected());
    ClientListner cl = new ClientListner(client);
    while (client.getSocket().isConnected()) {
        int key = 10;

            if (client.getInput().hasNext()) {
                txt_ChatPerson2.setText(client.reciveString());
                txt_ChatPerson2.setVisible(true);
            }
            try {
                key = client.reciveCommando();
                System.out.println("jeg er her");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        System.out.println("Key "+key);
        switch (key) {
        // case 2 er recive chat:
        case 2:
            // først find ud af hvilket ID der har sendt chatten:
            int y = 0;
            try {
                y = client.reciveCommando();
                System.out.println("y" + y); 
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // derefter få beskeden og send den så ud til resten.
            String says = client.reciveChat().toString();
            System.out.println("Says :"+says);
            if (y == 1) {
                txt_ChatPerson1.setText(says);
                txt_ChatPerson1.setVisible(true);
            }else if (y == 2) {
                txt_ChatPerson2.setText(says);
                txt_ChatPerson2.setVisible(true);
            }else {
                chatPerson3.setVisible(true);
                txt_ChatPerson3.setVisible(true);
                txt_ChatPerson3.setText(says);
            }

            break;

        default:
            break;
        }
    }
}

客户端类

 import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;


public class Client {
// disse var static
    public final static int portNumber = 6040;
    public Socket socket;
    private PrintWriter pw;
    private Scanner input;
    private int clientId;
    /**
     * @param args
     * @throws IOException 
     */

    public Client(Socket socket, PrintWriter pw, Scanner input, int clientId){
        this.socket = socket;
        this.pw = pw;
        this.input = input;
        this.clientId = clientId;
    }
    public void connect() throws IOException{
        // du kan vælge at bruge inetadressen til at connecte i socketet.
        InetAddress adr = InetAddress.getByName("localhost");
        socket = new Socket("localhost", portNumber);
        input=new Scanner(socket.getInputStream());
        pw = new PrintWriter(socket.getOutputStream());

    }
    /**
     * This method sends the message (that the client(chat person) writes to the user)
     * @param x
     * @throws NullPointerException
     * @throws IOException 
     */
    public void SendChat(String x) throws NullPointerException{
            pw.print("CHAT:"+x);
            pw.flush();
        /*  pw.println(2);
            pw.flush();
            pw.println(SimpleController.currentClientId);
            pw.flush();
            pw.println(x);
            pw.flush(); 
        */
    }
    public int sendCommando(int id) throws IOException{
        System.out.println("Jeg sender"+ id);
        pw.println(id);
        pw.flush();
        /*
         * this part of the program sends a command to the server if the command is 1 then 1 is = Connect.
         * the program then ask the server is the server is full or is it ok to connect? 
         * if the response is not 10 then the program will allow a connection to happen the return type will be the Id of which 
         * the chat person becomes!
         */
        // should the method return 0 the Application will do NOTHING!
        switch (id) {
        case 1:
    int k = reciveCommando();
            if (k== 10) {
                return 10;
            }else if (k < 3) {
                System.out.println("returned k" + k);
                return k;
            }else {

            return 10;
            }
            /*
             * Closes the connection with the server!
             */
        case 3:

            socket.close();
            return 0;

        case 5:
            int y  = reciveCommando();
            return y;

        case 8:
            return 8;
        default:
            return 0;
        }

    }
    /*
     * this method recives a command from the server! the comands can be found in the ChatCommands.txt
     * returns the command as an integer!
     */
    public int reciveCommando() throws IOException{
        Integer i = input.nextInt();
        return i;
    }
    /**
     * Gets a String response from the server. This method i used to create other users and give them the correct username.
     * 
     * @param i
     * @return
     * @throws IOException
     */
    public String getStringResponse(int i) throws IOException {
        pw.print(i);
        pw.flush();
        String x = input.nextLine();
        return x;

    }
/*
 * Work in progress - client getter og setter methoder!
 */

public Socket getSocket(){
    return socket;
}
public Scanner getInput(){
    return input;
}
public PrintWriter getPw(){
    return pw;
}
public int getClientId(){
    return clientId;
}

public void setClientId(int i ){
    clientId = i;
}
public String reciveChat(){
        return getInput().nextLine();

}
public String reciveString(){
    String x =input.next();
    return x;
}
public void sendString(String x){
    pw.println(x);
    pw.flush();
}



}

服务器代码

    import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class Server extends Thread {

    private Socket connection;
    private PrintWriter pw;
    private Scanner input;
    private ServerInformation info = new ServerInformation();
    private ChatPerson p;

    public Server(Socket connection, PrintWriter pw, Scanner input){
        this.connection = connection;
        this.pw = pw;
        this.input = input;
    }

    @Override
    public void run() {
        while (connection.isConnected()) {
            if (input.hasNextInt()) {
                System.out.println("Det var sgu da en int");
                int i = getInput().nextInt();
                System.out.println(i);
                checkCommand(i);    
            }else if (input.hasNext()) {
                System.out.println("det var ikke en int");
                String inString = input.nextLine();
                System.out.println(inString);
                chatCase(inString);
            } 
        }


    }
    private void chatCase(String x) {
        String k =x.substring(6 , x.length());
        System.out.println("k "+k);
        pw.print(x);

        pw.flush();
    }

    private void checkCommand(int i) {
        System.out.println("i "+i);
        switch (i) {
        // this case accepts the connection and creates a new user;
        case 1:


int id = info.getNextID();
        pw.println(1);
        pw.flush();
        pw.println(id);
        pw.flush();
        p = new ChatPerson(id, input.next());
        info.addToList(p);
        break;

        // this is the chat case virker ikke endnu
    case 2:
        int clientID = input.nextInt();
        String x = reciveString();
        System.out.println(x);
        pw.println(clientID);
        pw.flush();
        pw.print(x);
        pw.flush();
        break;
    // this case sends information about other chat users to the client
    case 5:
        pw.println(5);
        pw.flush();
        pw.println(info.getList().size());
        pw.flush();
        for (int j = 0; j < info.getList().size(); j++) {
            pw.println(info.getList().get(j).getId());
            System.out.println("info.get "+info.getList().get(j).getId());
            pw.flush();
            pw.println(info.getList().get(j).getName());
            pw.flush();
        }
        break;

    case 8:
        pw.println(8);
        pw.flush();
        break;
    default:
        break;
    }

}

private String reciveString() {
    if (input.next().contains(" ")) {
        String x = input.nextLine();
        return x;
    }
    return input.next();
}

public Socket getConnection(){
    return connection;
}
public PrintWriter getPw(){
    return pw;
}
public Scanner getInput(){
    return input;
}




}

我希望有人能够帮助我,因为这对我来说是一个大问题,如果您需要更多信息,请发表评论并尽可能多地提供

i hope someone is able to help me since this is a huge problem for me if you need more info please just comment and il provide as much as possible

推荐答案

你必须重新设计你的程序.

You have to rework your program.

  1. GUI 元素应仅从 GUI 线程 (EDT) 内更新,而不是从独立线程更新.

  1. GUI elements should be updated from within the GUI thread (EDT) only, not from a standalone thread.

客户端连接应该分为两个弱连接部分:发送消息和接收消息.接收应该是一个单独的线程,发送可以是一个线程或一个类.

Client connection should be divided in 2 weakly connected parts: sending messages and receiving them. Receiving should be a separate thread, and sending can be a thread or a class.

当接收线程读取消息时,它使用SwingUtilities.invokeLater(Runnable) 将其发送到EDT.示例可以在别处找到.

When the receiving thread have read a message, it sends it to EDT using SwingUtilities.invokeLater(Runnable). Examples can be found elsewhere.

当用户输入文本时,文本将直接发送到套接字,或者放入队列中,稍后由发送线程处理(如果有).

When user have entered text, the text is send to the socket directly, or enqueued in a queue and later processed by the sending thread, if any.

这篇关于服务器/客户端程序在线程启动后停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆