爲什麼要獲取NullPointerException
?當我從服務器發送數據到客戶端時,它一切正常。Java套接字從客戶端發送數據到服務器
Error java.lang.NullPointerException
at NetworkClient.Klient.wyslijDane(Klient.java:35)
編輯代碼 我添加了完整的服務器類和客戶端類 在其他類我創建了一個新的對象客戶端和服務器
klient =新Klient(); ,然後調用WyslijDane方法。服務器沒問題,客戶端拋出異常。
客戶端類
public class Klient {
public static final int PORT=50007;
public static Socket sock;
public static int msg=10;
public Klient() throws UnknownHostException, IOException
{
Socket sock=new Socket("localhost", PORT);
}
public static void wyslijDane(int GraczK) throws IOException
{
DataInputStream in=new DataInputStream(sock.getInputStream());
DataOutputStream out=new DataOutputStream(sock.getOutputStream());
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
out.writeInt(GraczK);
//out.writeBoolean(flaga);
out.flush();
System.out.println("Wyslano dane "+ GraczK);
}
}
服務器類
public class Server
{
public static final int PORT=50007;
public static MainWarSever main=new MainWarSever();
static Socket sock;
public Server() throws IOException
{
//tworzenie gniazda serwerowego
ServerSocket serv = null;
if (serv==null)
serv=new ServerSocket(PORT);
else
{
System.out.println("SErver już zajety brrrr");
serv.close();
}
sock=serv.accept();
System.out.println("Jest polaczenie: "+sock);
}
public static void wyslijDane(int GraczK) throws IOException
{
DataInputStream in=new DataInputStream(sock.getInputStream());
DataOutputStream out=new DataOutputStream(sock.getOutputStream());
boolean flaga=true;
int msg;
int i=0;
int msgOut;
msgOut=GraczK;
out.writeInt(msgOut);
out.writeBoolean(flaga);
out.flush();
System.out.println("Wyslano dane "+ GraczK + "Flage" + flaga);
}
一個是35行嗎? – CtrlAltDel
它的這一行35 \t \t DataOutputStream out = new DataOutputStream(sock.getOutputStream()); Set Sock Client \t public static final int PORT = 50007; \t public static Socket sock; \t public static int msg = 10; \t \t \t公共Klient()拋出的UnknownHostException,IOException異常 \t { \t \t插座襪子=新的Socket( 「本地主機」,PORT); \t} – Pekus
你可以編輯你的問題,並添加你創建套接字(在客戶端)的代碼部分? – CtrlAltDel