为什么要获取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