最近正在用Unity做一个类似三国杀的卡牌游戏,网上也找不到什么东西参考,只好自己动手一点点解决问题,由于服务器不是很熟,于是决定一边学Photon一边先做个局域网联机的玩玩,局域网联机我决定参考CS红警等游戏的模式先做个大厅一人建主其他人加入这种,毕竟直接输ip什么的太low了。
局域网联机说白了就是建主主机既是客户端也是服务器端,我选择选用UDP广播搞定大厅的问题,在用TCP连接主机和服务器。
大概流程如下:
1、 一个客户端创建房间,成为服务器端,开始监听;
2、客户端点击局域网联机后向全网广播UDP请求服务器端,
3、服务器收到消息,向客户端发送IP及端口号(房间信息,比如当前人数)
4、客户端接收并将收到的服务器房间显示在大厅中
5、客户端加入房间,和服务器建立TCP连接
之前为了逻辑清楚还在文档里画了图也放这里吧
这里的所有UDP都默认开启监听
这里的Server端同时也要创建TCPServer准备进行和客户端的正式连接
以下是测试图
输入姓名确认然后点创建
building好新开一个,点一下刷新
点加入
服务器客户端显示都如上图,这时候服务器和客户端都已经建立好连接了,开始游戏上注册上发送方法就行了,方法什么的都简单的封装过了,局域网亲测没问题。不过这里的可能会有一些小问题或者没做的比如返回关闭页面什么的,其实后来已经做了,但是游戏进度做了一些,删东西太麻烦就直接用之前的了,整体没啥问题的。
注意:如果是在同一主机测试,要把场景中EthernetManager上的端口改一下,保证打开的每一个程序的端口号不一样,多个主机就不用了,原因是UDP广播固定端口号,但是单机测试用回环ip,一个端口是不能开两个udpSocket的,默认广播端口9876,可以自己在代码改,如果单机测试记得用9876的程序来建主
EthernetManager中的代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using LitJson;
using System.Text;
using System;
public class EthernetManager : MonoBehaviour
{
private static EthernetManager _instance;
public static EthernetManager instance
{
get
{
return _instance;
}
set
{
_instance = value;
}
}
private SocketClient client = null;
private SocketTcpServer tcpServer = null;
private SocketTcpClient tcpClient = null;
public List<RoomInfo> roomList = new List<RoomInfo>();
public Dictionary<int, Client> ClientList = new Dictionary<int, Client>();
public List<RoomMemberInfo> rmiList = new List<RoomMemberInfo>();
public EndPoint tempRoomEp = null;
EndPoint host = null;
public Thread t = null;
public Thread l = null;
public Thread tcpListen = null;
public Thread clientListen = null;
public int port;
public bool shutClientListen = false;
public string clientReceiveMessage = null;
p