为什么这个套接字为空?

时间:2013-04-20 02:16:40

标签: java sockets null connection serversocket

我正在创建一个多客户端聊天服务器,我非常有信心它会工作(纠正我,如果我错了),我有问题,在客户端连接到的套接字是空的,所以连接可以'因为我使用if(Socket!= null)所以我不会出错,但我会快速解释我的布局。服务器以名为(LaunchServer)的入门类启动,该类使用类对象ClientConnector作为Minecraft,然后启动方法runServer()。以下是此类的代码:

public class LaunchServer
{
    public static void main(String[] args)
    {
        System.out.println("[Info] Running");
        ClientConnector Minecraft = new ClientConnector();
        Minecraft.runServer();
    }
}

这很简单。这将我们带到ClientConnector类。这里我们从方法runServer()开始。马上我们有一个try catch块。在该块中,我们打印一条消息,服务器正在尝试连接到端口1337.然后我们创建一个名为serversocket的新ServerSocket。然后我们向控制台发送一条消息说我们已经绑定了端口并且我们正在等待连接。虽然如此,我们创建一个新的Socket套接字,它等于ServerSocket.accept();天哪,他妈的。继承人的代码。你知道它的作用......

import java.util.ArrayList;
import java.net.*;
import java.io.*;

public class ClientConnector
{

public static ArrayList<Socket> Connections = new ArrayList<Socket>();

public static void runServer()
{
    try
    {   
        System.out.println("[Info] Attempting to bind to port 1337.");
        @SuppressWarnings("resource")
        ServerSocket serversocket = new ServerSocket(1337);
        System.out.println("[Info] Bound to port 1337.");
        System.out.println("[Info] Waiting for client connections...");
        while(true)
        {
            Socket socket = serversocket.accept();
            new ClientHandler(socket).start();
            Connections.add(socket);
        }

    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
}

这将我们带到处理程序类:

import java.io.*;
import java.net.*;


public class ClientHandler extends Thread
{
Socket Socket;

public ClientHandler(Socket socket)
{
    socket = Socket;
    System.out.println("[Info] Client connected on port 1337.");
}

public void run()
{
    while(true)
    {
        for(int i = 0; i < ClientConnector.Connections.size(); i++)
        {

            try
            {
                if(Socket != null)//This stays null...
                {
                    ObjectOutputStream Output = new //These can't be created... 
                    ObjectOutputStream(Socket.getOutputStream());
                    ObjectInputStream Input = new ObjectInputStream(Socket.getInputStream());
                    whileChatting(Input, Output);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

public static void sendMessage(String message, String returnedMessage, ObjectOutputStream out)
{
    try
    {

        if(!message.isEmpty())
        {
            out.writeObject("\247c[Server]\247d " + message);
            out.flush();
            System.out.println("[Chat] Sent: " + message);
        }
        else
        {
            out.writeObject(returnedMessage);
            System.out.println("[Chat] Sent: " + returnedMessage);
        }
        out.flush();
        System.out.println("[Info] Fluching remaining data to stream.");
        System.out.println("\n[Server] " + message);
    }
    catch(IOException ioException)
    {
        System.out.println("[Warning] Error: ioException @ sendMessage line 76.");
    }
 }

public static void whileChatting(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
    String message = "";
    do
     {
         try
         {
             message = (String) input.readObject();
             System.out.println("\n" + message);
             sendMessage("", message, output); 
         }
         catch(ClassNotFoundException classNotFoundException)
         {
             System.out.println("[Warning] Error: ClassNotFoundException @ whileChatting line 1-7.");
             System.out.println("\n idk wtf that user sent!");
         }
     }while(!message.equals("/stop"));
 }


}

阅读run方法。在那里你会看到null问题

连接是否会被接受然后传递给hander类?如何接受空连接?我的问题是如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

问题是由于不推荐的命名约定,您遇到了逻辑错误。您不应该使用关键字命名变量,例如Socket变量,并且每个变量都应该具有可区分的名称。例如不是socket1, socket2而是serverSocket, clientSocket,因为这样可以让您和其他任何人更轻松地阅读和修复您的代码。

更改

Socket Socket;

Socket connectedSocket;

并在您的构造函数中

socket = Socket;

connectedSocket = socket;

最后,在run()方法更改

if(Socket != null)

if(connectedSocket != null)