gpt4 book ai didi

java - socket 乱七八糟

转载 作者:行者123 更新时间:2023-11-30 07:17:47 25 4
gpt4 key购买 nike

我关于套接字的代码分为三个类,现在我已经研究它(并学习套接字 Api)几个小时了,我已经把它归结为只剩下一个错误(我可以看)。从服务器收到的消息将不会打印,而是抛出此错误。

Exception in thread "Thread-14" java.lang.NullPointerException main.Listen.run(Listen.java:11) java.lang.Thread.run(Unknown Source)

控制台类

package main;

public class Console extends Handle {

String nextl = System.getProperty("line.separator");
String info = "[INFO] ";
String ser = "[SERVER] ";
String err = "[ERROR] ";
String name = "[" + userName + "] ";

public void log() {
startupCon();
Network network = new Network();
int allgood = network.connect();
if (allgood == 34) {
Listen listen = new Listen();
new Thread(listen).start();
}
}

void startupCon() {

System.out.println("===========");
System.out.println("=+CONSOLE+=");
System.out.println("===========" + nextl);
}

void networkCon(String net) {
System.out.println(net);
}

}

网络类:

package main;

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

public class Network extends Console {

int port = 7771;
String host = "localhost";
Socket client;

OutputStream outToServer;
DataOutputStream out;
InputStream inFromServer;
DataInputStream in;

public int connect() {
int getOpen = open();
System.out.println(getOpen);
int getStream = trans(getOpen);
System.out.println(getStream);
return getStream;
}

int open() {
try {

networkCon(info + "Attemping to connect to /" + host + ":" + port);
client = new Socket(host, port);
System.out.println(info + "Established connection with "
+ client.getRemoteSocketAddress());
return 42;
} catch (SocketTimeoutException s) {
networkCon(err + "Socket timed out!");
return 9;
} catch (IOException e) {
System.out.println(err + "Could not connect to /" + host + ":"
+ port);
return 9;
}
}

int trans(int hostup) {
if (hostup == 42) {
try {
outToServer = client.getOutputStream();
out = new DataOutputStream(outToServer);
inFromServer = client.getInputStream();
in = new DataInputStream(inFromServer);
return 34;
} catch (SocketTimeoutException s) {
networkCon(err + "Socket timed out!");
return 8;
} catch (IOException e) {
System.out.println(err + "Connection lost!");
return 8;
}
}
return 7;
}

}

听课(我存在的祸根)

package main;

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

public class Listen extends Network implements Runnable {

public void run() {
while (true) {
try {
networkCon(in.readUTF());
} catch (SocketTimeoutException s) {
networkCon(err + "Socket timed out!");
} catch (IOException e) {
System.out.println(err + "Connection lost!");
}
}

}
}

我猜测 Stream 没有在 Listen 类中设置为变量“in”,但我不知道这是否是问题所在或如何解决它。

最佳答案

你没有在任何地方调用 Network 类的方法 connect()。这就是为什么你的 DataInputStream in 永远不会被初始化的原因。它是在你的程序中总是null..

我猜你应该在 Listen 类中定义一个构造函数,你调用父类(super class) Networkconnect 方法如下:

public Listen()
{
connect();
}

关于java - socket 乱七八糟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15822569/

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