107 lines
2.7 KiB
Java
107 lines
2.7 KiB
Java
|
|
package uno.mloluyu.network;
|
|||
|
|
|
|||
|
|
import com.badlogic.gdx.Gdx;
|
|||
|
|
import java.util.ArrayList;
|
|||
|
|
import java.util.List;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 网络管理器,协调服务器和客户端通信
|
|||
|
|
*/
|
|||
|
|
public class NetworkManager {
|
|||
|
|
private static NetworkManager instance;
|
|||
|
|
private ConnectServer server;
|
|||
|
|
private ConnectClient client;
|
|||
|
|
private boolean isHost = false;
|
|||
|
|
private List<String> playerPositions = new ArrayList<>();
|
|||
|
|
|
|||
|
|
public static NetworkManager getInstance() {
|
|||
|
|
if (instance == null) {
|
|||
|
|
instance = new NetworkManager();
|
|||
|
|
}
|
|||
|
|
return instance;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 创建房间(作为主机)
|
|||
|
|
*/
|
|||
|
|
public void createRoom() {
|
|||
|
|
isHost = true;
|
|||
|
|
server = new ConnectServer(11455);
|
|||
|
|
new Thread(server).start();
|
|||
|
|
Gdx.app.log("Network", "房间创建成功,等待其他玩家加入...");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 加入房间(作为客户端)
|
|||
|
|
*/
|
|||
|
|
public void joinRoom(String ip) {
|
|||
|
|
isHost = false;
|
|||
|
|
client = new ConnectClient(ip, 11455);
|
|||
|
|
Gdx.app.log("Network", "正在加入房间: " + ip);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 发送玩家位置信息
|
|||
|
|
*/
|
|||
|
|
public void sendPosition(float x, float y) {
|
|||
|
|
if (isHost && server != null) {
|
|||
|
|
// 主机直接广播位置
|
|||
|
|
broadcastMessage("POS:" + x + "," + y);
|
|||
|
|
} else if (client != null) {
|
|||
|
|
// 客户端发送位置到服务器
|
|||
|
|
client.sendMessage("POS:" + x + "," + y);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 广播消息(主机使用)
|
|||
|
|
*/
|
|||
|
|
private void broadcastMessage(String message) {
|
|||
|
|
// 这里需要实现广播逻辑
|
|||
|
|
Gdx.app.log("Network", "广播消息: " + message);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取其他玩家位置
|
|||
|
|
*/
|
|||
|
|
public List<String> getOtherPlayerPositions() {
|
|||
|
|
return playerPositions;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 断开连接
|
|||
|
|
*/
|
|||
|
|
public void disconnect() {
|
|||
|
|
if (server != null) {
|
|||
|
|
server.dispose();
|
|||
|
|
server = null;
|
|||
|
|
}
|
|||
|
|
if (client != null) {
|
|||
|
|
client.disconnect();
|
|||
|
|
client = null;
|
|||
|
|
}
|
|||
|
|
playerPositions.clear();
|
|||
|
|
Gdx.app.log("Network", "网络连接已断开");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public boolean isHost() {
|
|||
|
|
return isHost;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public boolean isConnected() {
|
|||
|
|
return server != null || client != null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void updatePlayerPosition(String positionData) {
|
|||
|
|
// 简单实现:直接存储位置数据
|
|||
|
|
playerPositions.add(positionData);
|
|||
|
|
|
|||
|
|
// 限制位置列表大小,避免内存泄漏
|
|||
|
|
if (playerPositions.size() > 10) {
|
|||
|
|
playerPositions.remove(0);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Gdx.app.log("Network", "更新其他玩家位置: " + positionData);
|
|||
|
|
}
|
|||
|
|
}
|