在JAVA中启用ServerSocket后,无操作

时间:2016-04-15 18:46:19

标签: java eclipse serversocket

我创建了一个服务器套接字并启用它来监听传入的流。但是在启用连接后,它应该显示一个对话框,显示消息"服务器已启动" ,但它没有出现。我注意到在启用套接字之后没有代码。我试过很多关于这个但是似乎找不到合适的答案。这是我的代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Server
{
public Server(int i1) throws Exception{

    ServerSocket MySock=new ServerSocket(i1);//opening server socket
    Socket Sock=MySock.accept();//listening to client enabled 
    JOptionPane.showMessageDialog(null, "Server Started");
    }
public static void main(String[] args) {
   try {
    new Server(2005);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
      }
}
}   

1 个答案:

答案 0 :(得分:0)

问题在于ServerSocket.accept()blocks until a connection is made.

因此,只有有人连接到serversocket才会执行JOptionPane.showMessageDialog(...)

这是一个在单独的线程中处理ServerSocket的解决方案

import java.io.IOException;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;

public class Server
{
    public Server(int i1) throws Exception{

        Runnable serverTask = () -> {

            try {
                ServerSocket MySock=new ServerSocket(i1);//opening server socket

                while (true) {
                    Socket Sock=MySock.accept();//listening to client enabled
                    System.out.println("Accept from " + Sock.getInetAddress());
                }
            } catch (IOException e) {
                System.err.println("Accept failed.");
            }

        };

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(serverTask);

        JOptionPane.showMessageDialog(null, "Server Started");
    }

    public static void main(String[] args) {
        try {
            new Server(2005);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}