gpt4 book ai didi

java - 套接字 () - 错误 : variable client might not have been initialized

转载 作者:行者123 更新时间:2023-11-29 03:31:37 25 4
gpt4 key购买 nike

我写了一个很简单的客户端程序

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

public class GreetingClient
{
private Socket cSocket;

public GreetingClient() throws IOException
{
String serverName = "127.0.0.1";
int port = 5063;
cSocket = new Socket(serverName,port);
}


public static void main(String [] args)
{
GreetingClient client;
try
{
client = new GreetingClient();
}
catch(IOException e)
{
e.printStackTrace();
}

while (true)
{
try
{
InputStream inFromServer = client.cSocket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);

System.out.println("Server says " + in.readUTF());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}

当我编译这个程序时,我得到了这样的错误

GreetingClient.java:33: error: variable client might not have been initialized
InputStream inFromServer = client.cSocket.getInputStream();
^
1 error

这个错误是什么意思?如果 new Socket() 调用失败(例如,如果打开了太多套接字)那么这是否意味着我不能在代码中使用它?我如何处理情况像这样。?

最佳答案

try
{
client = new GreetingClient(); // Sets client OR throws an exception
}
catch(IOException e)
{
e.printStackTrace(); // If exception print it
// and continue happily with `client` unset
}

稍后您正在使用;

// Use `client`, whether set or not.
InputStream inFromServer = client.cSocket.getInputStream();

要修复它,要么在声明它的地方将 client 设置为 null(这可能会在以后使用时导致 nullref 异常),要么在打印异常后不要“盲目地”继续(例如, 打印并返回)。

关于java - 套接字 () - 错误 : variable client might not have been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17895861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com