我的问题如下:我有以下客户端类:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public final int portNumber = 6040;
public Socket socket;
private PrintWriter pw;
/**
* @param args
* @throws IOException
*/
public void connect() throws IOException{
// du kan vælge at bruge inetadressen til at connecte i socketet.
InetAddress adr = InetAddress.getByName("localhost");
socket = new Socket("localhost", portNumber);
pw = new PrintWriter(socket.getOutputStream());
pw.println("Connected waiting for input");
pw.flush();
}
/**
* This method sends the message (that the client(chat person) writes to the user)
* @param x
* @throws NullPointerException
* @throws IOException
*/
public void SendChat(String x) throws NullPointerException{
pw.print(x);
pw.flush();
}
public int sendCommando(int id) throws IOException{
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.print(id);
/*
* this part of the program sends a command to the server if the command is 1 then 1 is = Connect.
* the program then ask the server is the server is full or is it ok to connect?
* if the response is not 10 then the program will allow a connection to happen the return type will be the Id of which
* the chat person becomes!
*/
// should the method return 0 the Application will do NOTHING!
switch (id) {
case 1:
int k = reciveCommando();
if (k== 10) {
return 10;
}else if (k<= 3) {
return k;
}else {
return 10;
}
/*
* Closes the connection with the server!
*/
case 3:
socket.close();
return 0;
default:
return 0;
}
}
/*
* this method recives a command from the server! the comands can be found in the ChatCommands.txt
* returns the command as an integer!
*/
public int reciveCommando() throws IOException{
Scanner commandoFromServer = new Scanner(socket.getInputStream());
Integer i = Integer.parseInt(commandoFromServer.nextLine());
return i;
}
/**
* Gets a String response from the server. This method i used to create other users and give them the correct username.
*
* @param i
* @return
* @throws IOException
*/
public String getStringResponse(int i) throws IOException {
pw.print(i);
pw.flush();
Scanner commandFromServer = new Scanner(socket.getInputStream());
String x = commandFromServer.nextLine();
return x;
}
}
除此之外,我有一个用作“主”类的 GUI。
我有一个名为 SocketTest v3.0.0 的程序(如果你们中有人知道的话),它的基本作用是为我创建一个我可以连接的服务器。
现在我的程序运行并连接到服务器!但是当我尝试在我的客户端程序(除了连接)中调用方法 sendCommand 或 sendChat 或任何其他方法时,它会给我一个空指针执行。
我已将问题缩小到当我声明套接字时套接字为空我该如何解决这个问题?因为我无法在我的公共类下初始化套接字!
我希望你明白我的意思,如果没有,请回复,我会详细说明!
先感谢您!