我正在制作一个使用socket连接其他人的程序。当我发送String或String数组时,它工作正常。但是,当我尝试通过套接字发送对象时,它不起作用,并出现EOFException。 我试图通过自己找到它,但对我来说似乎太难了!
这是客户端中的输入功能: (我在这个函数中有很多案例,但它们工作正常,所以只是案例有问题)
public void run()
{
while(true)
{
try
{
int dataType = (int)in.readByte(); // this line is where the exception appeared. every works fine with another case
switch(dataType)
{
case 2:
{
try
{
int nRoom = (int)in.readByte(); // read the number of room are created
for (int i = 0; i < nRoom; i++)
{
Server.Room temp = (Server.Room) in.readObject();
nRooms[temp.ID] = temp;
}
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.toString());
}
}
break;
}
}
catch (EOFException e)
{
System.out.println(e.toString());
}
catch (IOException ex)
{
System.out.println(ex.toString());
break;
}
}
}
以下是客户端中的outPut函数:
private void createBtnClick( java.awt.event.ActionEvent evt )
{
try
{
out.writeByte(2);
out.flush();
}
catch (IOException ex)
{
System.out.println(ex.toString);
}
}
这是服务器接受输入然后将输出写入每个客户端的功能(在下面的代码中是用户):
public void run()
{
while(true)
{
try
{
int command = users[index].in.readByte();
switch ( command)
{
case 2:
// create the room
for (int i = 0; i < 5; i++)
{
if(nRooms[i] == null)
{
nRooms[i] = new Room(users[i].name,"Beginner", 1, i);
users[index].State = 1;
System.out.println("SV : create room ok " + i);
break;
}
}
for (int i = 0; i < 10; i++)
{
if(users[i] != null && i != index && ) // Send the room list to everybody except the room host!
{
try
{
users[i].out.writeByte(2);
int count = 0;
for (int j = 0; j < 5; j++)
{
if(nRooms[j] != null)
count++;
}
users[i].out.writeByte(count);
for (int j = 0; j < 5; j++)
{
if(nRooms[j] != null);
{
users[i].out.writeObject( nRooms[j]);
break;
}
}
//users[i].out.flush();
}
catch (IOException ex)
{
System.out.println(ex.toString());
}
}
}
break;
}
}
catch (IOException ex)
{
System.out.println(ex.toString());
users[index].in = null;
users[index].out = null;
users[index] = null;
break;
}
}
Room class只是一个包含一些信息的类:(在Server中定义)
public class Room implements Serializable
{
public String hostName;
public String gameMode;
public int nPlayers;
public int ID;
public Room(String hostName, String gameMode, int nPlayers, int ID)
{
this.hostName = hostName;
this.gameMode = gameMode;
this.nPlayers = nPlayers;
this.ID = ID;
}
}
谢谢!