Java Server类和套接字连接问题

时间:2016-04-20 02:22:28

标签: java sockets server client

我正在尝试设置一个服务器类,并且我遇到了一个没有抛出错误的问题。

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

public class Server extends JFrame implements Runnable{

private static final long serialVersionUID = 1L;
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;

//constructor
public Server(){
    super("Server");
    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();
    add(new JScrollPane(chatWindow));
    setSize(300, 150); //Sets the window size
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);   
}

public void run(){
    try{
        server = new ServerSocket(6789, 100); //6789 is a dummy port for testing, this can be changed. The 100 is the maximum people waiting to connect.
        while(true){
            try{
                //Trying to connect and have conversation
                waitForConnection();
                setupStreams();
                whileChatting();
            }catch(EOFException eofException){
                showMessage("\n Server ended the connection! ");
            } finally{
                closeConnection(); //Changed the name to something more appropriate
            }
        }
    } catch (IOException ioException){
        ioException.printStackTrace();
    }
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException{
    showMessage(" Waiting for someone to connect... \n");
    connection = server.accept();
    showMessage(" Now connected to " + connection.getInetAddress().getHostName());
}

//get stream to send and receive data
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();

    input = new ObjectInputStream(connection.getInputStream());

    showMessage("\n Streams are now setup \n");
}

//during the chat conversation
private void whileChatting() throws IOException{
    String message = " You are now connected! ";
    sendMessage(message);
    ableToType(true);
    do{
        try{
            message = (String) input.readObject();
            showMessage("\n" + message);
        }catch(ClassNotFoundException classNotFoundException){
            showMessage("The user has sent an unknown object!");
        }
    }while(!message.equals("CLIENT - END"));
}

public void closeConnection(){
    showMessage("\n Closing Connections... \n");
    ableToType(false);
    try{
        output.close(); //Closes the output path to the client
        input.close(); //Closes the input path to the server, from the client.
        connection.close(); //Closes the connection between you can the client
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

//Send a mesage to the client
private void sendMessage(String message){
    try{
        output.writeObject("SERVER - " + message);
        output.flush();
        showMessage("\nSERVER -" + message);
    }catch(IOException ioException){
        chatWindow.append("\n ERROR: CANNOT SEND MESSAGE, PLEASE RETRY");
    }
}

//update chatWindow
private void showMessage(final String text){
    SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                chatWindow.append(text);
            }
        }
    );
}

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



import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Menu extends JFrame implements ActionListener{

private static final long serialVersionUID = 1L;
private JButton server;
private JButton client;
private static String Host;

public Menu(){

    this.getContentPane().setPreferredSize(new Dimension(300, 300));

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(null);
    this.pack();

    this.setLocationRelativeTo(null);

    server = new JButton();
    server.setText("server");
    server.setBounds(0, 0, 300, 150);
    server.addActionListener(this);
    client = new JButton();
    client.setText("client");
    client.setBounds(0, 150, 300, 150);
    client.addActionListener(this);

    this.add(server);
    this.add(client);

    this.setVisible(true);
}


public void actionPerformed(ActionEvent e) {
    if(e.getSource() == server){
        Server s = new Server();
        s.run();
    }
    if(e.getSource() == client){
        Host = JOptionPane.showInputDialog("Enter Server I.P.");
        Client c = new Client(Host);
        c.run();
    }

}

public static void main(String[] args){
    new Menu();
}

}

JFrame已创建,但只能通过eclipse中的终止按钮退出,而不能通过default_exit_on_close操作退出,并且是透视的(不应该是不透明的)。客户端类的行为方式相同,让我相信问题是:

 Server s = new Server();
        s.run(); 

因为如果我有主方法调用,那么一切正常。

1 个答案:

答案 0 :(得分:0)

您的构造函数永远无法退出。

#!/bin/bash RESULT1=$(ps -ef | grep "sudo tcpdump" | grep -v grep) RESULT2=$(ps -ef | grep "sudo tcpdump" | grep -v grep | awk '{print $3}') echo $RESULT1 echo $RESULT2 #Validate existence of PPID before asking for input if test -z "$RESULT2"; then ## If no PPIDs echo 'No PPID value found' && exit 1 else echo "Choose which PPID to kill" read input fi # Get result of whether input matches a value in RESULT2 res=`echo $RESULT2 | grep $input` # If input is empty, then if test -z "$input"; then echo "input empty" && exit 1 elif test -z "$res"; then # If input doesn't match PPID listed echo "input doesn't match PPID" && exit 1 else pkill -P $INPUT #kill PPID fi exit 0 逻辑不合适。你需要一个接受循环,只接受套接字,构造一个waitForConnection()/setUpStreams()来处理连接,并启动一个线程。该循环应该在一个单独的Runnable方法中,并在一个单独的线程中执行。不在构造函数中。

注意run()返回的Socket必须是该循环中的局部变量,否则您可能会遇到并发问题。