程序冻结(Java)

时间:2015-10-31 16:53:00

标签: java swing concurrency

所以,我编写了这个消息传递程序,并尝试实现客户端可以将朋友添加到列表中的功能。但是,每当它试图连接客户端冻结的所有东西时。服务器连接,除了客户端程序之外的所有东西都冻结了。当我尝试发送消息时,它无法到达那里。但是,当我关闭服务器时,一切都会立即发送到客户端,然后关闭。 (另外,我知道我有很多导入,但是当我的程序运行时我会修复它)。此外,如果你发现一些与这个问题无关的愚蠢,如果你告诉我,我会很高兴,我还在学习。任何帮助,将不胜感激! C:

我的课程:

Main(In" Server"项目):

import javax.swing.JFrame;
public class Main {
    public static void main(String[] args){
        Server server = new Server();
        server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        server.setVisible(true);
        server.startServer();
    }
}

服务器:

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


public class Server extends JFrame{

private JTextArea chatWindow;
private JTextField inputField;
private JTextField nameField;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private String name = "Name";

public Server(){
    super("Zyph's Chat Server");

    chatWindow = new JTextArea();
    inputField = new JTextField();
    nameField = new JTextField("Name");

    chatWindow.setEditable(false);
    inputField.setEditable(false);

    inputField.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent event) {
            if(event.getActionCommand().equals("/clear")){
                chatWindow.setText("");
            }

            sendMessage(event.getActionCommand());
            inputField.setText("");
        }

    });

    nameField.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent event) {
            if(!(event.getActionCommand().equals(""))){
                name = event.getActionCommand();
            }
        }

    });


    add(new JScrollPane(chatWindow), BorderLayout.CENTER);
    add(inputField, BorderLayout.SOUTH);
    add(nameField, BorderLayout.NORTH);
    setSize(720, 480);
}

public void startServer(){
    try{
        server = new ServerSocket(6789, 100);
        while(true){
            try{
                waitForConnection();
                setupStreams();
                whileChatting();
            }catch(EOFException e){
                showMessage("Server closed connection...");
            }finally{
                closeConnection();
            }
        }
    }catch(IOException e){
        e.printStackTrace();
    }
}

private void waitForConnection() throws IOException{
    showMessage("Waiting for connection...");
    connection = server.accept();
    showMessage("You are now connected to " +      connection.getInetAddress().getHostName());
}

private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("Output and input is up!");
}

private void whileChatting() throws IOException{
    String message = "You can now chat!";
    showMessage(message);
    ableToType(true);
    do{
        try{
            message = (String) input.readObject();
            showMessage(message);
        }catch(ClassNotFoundException e){
            showMessage("Error: Unknown syntax sent from user");
        }
    }while(!message.contains(" - /end"));
}

private void closeConnection(){
    showMessage("Closing connection...");
    ableToType(false);
    try{
        output.close();
        input.close();
        connection.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

private void sendMessage(String message){
    try{
        output.writeObject(name + " - " + message);
        output.flush();
        showMessage(name + " - " + message);

    }catch(IOException e){
        chatWindow.append("\nError: Can't send message");
    }
}

private void showMessage(final String message){
    SwingUtilities.invokeLater(
            new Runnable(){
                public void run(){
                    chatWindow.append("\n" + message);
                }

            }
    );
}

private void ableToType(final boolean att){
    SwingUtilities.invokeLater(
            new Runnable(){
                public void run(){
                    inputField.setEditable(att);
                }
            });
}

}

主要(在"客户"项目中):

import javax.swing.JFrame;

public class Main{
    public static void main(String[] args){
    Client client = new Client("192.168.1.3"); //127.0.0.1
    client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    client.setVisible(true);
    client.startRunning();
}
}

客户端:

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class Client extends JFrame{

private JTextArea chatWindow;
private JTextField inputField;
private JTextField nameField;
private JList<String> friends;
private DefaultListModel<String> friendsListModel;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
private String name = "Name";
private File friendFile = new File("C:\\Users\\Aztro\\Desktop\\Friends.txt");
private Scanner scanner;

public Client(String host){
    super("Zyph's Chat Client");
    serverIP = host;
    chatWindow = new JTextArea();
    inputField = new JTextField();
    nameField = new JTextField("Name");
    friendsListModel = new DefaultListModel<String>();
    fileToFriend();
    friends.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    chatWindow.setEditable(false);
    inputField.setEditable(false);
    inputField.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event){
            if(event.getActionCommand().equals("/add")){
                try {
                    BufferedWriter bf = new BufferedWriter(new FileWriter(friendFile));
                    bf.append(connection.getInetAddress().getHostAddress());
                    friendsListModel.addElement(connection.getInetAddress().getHostAddress());
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            sendMessage(event.getActionCommand());
            inputField.setText("");
        }

    });

    nameField.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent event) {
            if(!(event.getActionCommand().equals(""))){
                name = event.getActionCommand();
            }
        }

    });

    friends.addListSelectionListener(new ListSelectionListener(){
        @Override
        public void valueChanged(ListSelectionEvent event) {
            serverIP = friends.getSelectedValue();
            friends.clearSelection();
            startRunning();
        }
    });

    add(new JScrollPane(chatWindow), BorderLayout.CENTER);
    add(new JScrollPane(friends), BorderLayout.WEST);
    add(nameField, BorderLayout.NORTH);
    add(inputField, BorderLayout.SOUTH);
    setSize(720, 480);

}

public void startRunning(){
    try{
        connectToServer();
        setupStreams();
        whileChatting();
    }catch(EOFException e){
        showMessage(name + " closed connection...");
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        closeConnection();
        showMessage("You are no longer connected");
    }
}

private void connectToServer() throws IOException{
    showMessage("Connecting to server...");
    connection = new Socket(InetAddress.getByName(serverIP), 6789);
    showMessage("You are now connected to " + connection.getInetAddress().getHostName());
}

private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("Output and input is up!");
}

private void whileChatting() throws IOException{
    ableToType(true);
    showMessage("You are now able to chat!");
    do{
        try{
            message = (String) input.readObject();
            showMessage(message);
        }catch(ClassNotFoundException e){
            showMessage("Error: Unknown syntax");
        }
    }while(!message.contains(" - /end"));
    }

private void closeConnection(){
    showMessage("Closing connection...");
    ableToType(false);
    try{
    output.close();
    input.close();
    connection.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

private void sendMessage(String message){
    try{
        output.writeObject(name + " - " + message);
        output.flush();
        showMessage(name + " - " + message);
    }catch(IOException e){
        chatWindow.append("Error: Can't send message");
    }
}

private void showMessage(final String message){
    SwingUtilities.invokeLater(
            new Runnable(){
                public void run(){
                    chatWindow.append("\n" + message);
                }
            });
}

private void ableToType(final boolean tof){
    SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                inputField.setEditable(tof);
            }

            }
        );
    }
private void fileToFriend(){
    try{
        scanner = new Scanner(friendFile);
        while(scanner.hasNextLine()){
            friendsListModel.addElement(scanner.nextLine());
        }
        friends = new JList<String>(friendsListModel);
    }catch (Exception e){

        e.printStackTrace();
    }
}
}

0 个答案:

没有答案