我创建了一个java TCP游戏服务器并在端口1990上侦听新的传入连接。 我创建了一个Unity3D客户端来连接服务器并发送消息。问题是,我可以成功连接但是当我尝试发送消息时,它在我关闭套接字之前不起作用。它以某种方式保存数据的发送并在套接字关闭时发送它。
Unity C#客户端代码:
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 1990);
NetworkStream stream = client.GetStream();
stream.ReadTimeout = 10;
stream.WriteTimeout = 10;
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message From Client");
stream.Write(outStream, 0, outStream.Length);
stream.Flush();
Java Server代码:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.Vector;
public class Server {
public static volatile Vector<User> usersList = new Vector<>();
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(1990);
Socket socket = null;
DataInputStream in = null;
DataOutputStream out = null;
int i = 1;
while(true)
{
try {
socket = ss.accept();
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
// STARTING NEW DEDICATED THREAD
User user = new User(i, socket.getInetAddress().toString(), socket, in, out);
usersList.add(user);
user.start();
} catch (Exception e) { e.printStackTrace(); }
i++;
}
}
}
class User extends Thread {
int uid = -1;
int opponentUid = -1;
String ipAddress = null;
String data = null;
Socket s;
DataInputStream in;
DataOutputStream out;
User(int uid, String ipAddress, Socket s, DataInputStream in, DataOutputStream out) throws Exception
{
this.uid = uid;
this.ipAddress = ipAddress.replace("/", "");
this.s = s;
this.in = in;
this.out = out;
String temp = null;
while((temp = in.readLine()) != null) {
data = temp;
}
}
public void run()
{
System.out.println("\nUser Id: " + uid + "\nIP Address: " + ipAddress + "\nData: " + data);
try {
out.writeUTF(String.valueOf(uid));
} catch (Exception e1) { System.out.println("Client Error"); }
while(true)
{
try {
String temp = null;
while((temp = in.readLine()) != null) {
data = temp;
System.out.println("Client " + uid + ": " + data);
}
String[] vars = data.split("#"); // STRING SPLITTER TO GET THE DESTINATION IP
if(vars[0].equals("matchmaking"))
{
for(User client : Server.usersList)
{
if(client.opponentUid == -1 && client.uid != this.uid)
{
client.opponentUid = this.uid;
this.opponentUid = client.uid;
out.writeUTF("matched#" + String.valueOf(client.uid));
client.out.writeUTF("matched#" + String.valueOf(this.uid));
}
}
}
else if(vars[0].equals("message"))
{
for(User client : Server.usersList)
{
if(this.opponentUid == client.uid)
{
client.out.writeUTF(vars[1]);
break;
}
}
}
} catch (Exception e) {
System.out.println("Client " + uid + " Disconnected");
Server.usersList.remove((User)this);
break;
}
}
}
}
真的很感激任何帮助。感谢。