服务器
using System;
using System.Collections.Generic;
using System.Linq;
usingSystem.Net;
usingSystem.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace qunChatServer
{
class NetMgr : Singleton<NetMgr>
{
public Socket lister;
public byte[] buffer = new byte[2048];
public List<Socket> list = new List<Socket>();
/// <summary>
///开启服务器的方法
/// </summary>
public void StartServer()
{
lister = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
lister.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777));
lister.Listen(0);
Console.WriteLine("服务器已经开启侦听>>>>>>>");
lister.BeginAccept(Acceptcallback, null);
}
private void Acceptcallback(IAsyncResult ar)
{
Socket client = lister.EndAccept(ar);
IPEndPoint iep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("有客户端连入了,其ip为:{0},端口号为:{1}", iep.Address.ToString(), iep.Port);
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
}
/// <summary>
/// 接收
/// </summary>
/// <param name="ar"></param>
private void Receivecallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
list.Add(client);
int len = client.EndReceive(ar);
try
{
if (len > 0)
{
byte[] newbuffer = new byte[len];
Buffer.BlockCopy(buffer, 0, newbuffer, 0, newbuffer.Length);
string str = Encoding.UTF8.GetString(newbuffer);
Console.WriteLine("收到数据了,其内容为 :{0},长度为:{1}", str, newbuffer.Length);
foreach (Socket item in list)
{
SendMsg(item, str);
}
lister.BeginAccept(Acceptcallback, null);
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
}
else
{
CloseClient(client);
}
}
catch (Exception ex)
{
Console.WriteLine(client.LocalEndPoint + "连接失败!" + ex.Message);
}
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="item"></param>
/// <param name="str"></param>
private void SendMsg(Socket item, string str)
{
byte[] b = Encoding.UTF8.GetBytes(str);
item.Send(b);
}
private void CloseClient(Socket client)
{
Console.WriteLine(client.LocalEndPoint + "断开连接了");
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
}
客户端
using
System;
using
System.Collections;
using
System.Collections.Generic;
usingSystem.Net;
usingSystem.Net.Sockets;
using
System.Text;
using
UnityEngine;
public
class
NetMgr
: singleton<NetMgr>
{
public
Socket client;
public
byte
[] buffer =
new
byte
[2048];
public
Queue<
string
> queue =
new
Queue<
string
>();
///
<summary>
///
开启客户端的方法
///
</summary>
public
void
StartClient()
{
client =
new
Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(
new
IPEndPoint(IPAddress.Parse(
"127.0.0.1"
), 7777));
if
(client.Connected)
{
Debug.Log(client.LocalEndPoint +
"连接成功"
);
}
}
public
void
ReceiveMsg()
{
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
}
///
<summary>
///
接收
///
</summary>
///
<param name="
ar
"></param>
private
void
Receivecallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
int
len =
this
.client.EndReceive(ar);
try
{
if
(len > 0)
{
byte
[] newbuffer =
new
byte
[len];
Buffer.BlockCopy(buffer, 0, newbuffer, 0, newbuffer.Length);
string
str = Encoding.UTF8.GetString(newbuffer);
Debug.Log(
"收到数据了,其内容为:"
+ str);
queue.Enqueue(str);//入队
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, Receivecallback, client);
}
else
{
CloseClient(client);
}
}
catch
(Exception ex)
{
Debug.Log(client.LocalEndPoint +
"连接失败!"
+ ex.Message);
}
}
///
<summary>
///
发送信息
///
</summary>
///
<param name="
item
"></param>
///
<param name="
str
"></param>
public
void
SendMsg(
string
str)
{
byte
[] b = Encoding.UTF8.GetBytes(str);
client.Send(b);
}
private
void
CloseClient(Socket client)
{
Debug.Log(client.LocalEndPoint +
"断开连接了"
);
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
挂载在UI上
using
System;
using
System.Collections;
using
System.Collections.Generic;
using
UnityEngine;
public
class
ChatUI
: MonoBehaviour
{
public
UITextList list;
public
UIInput input;
public
UIButton btn;
void
Start
()
{
UIEventListener.Get(btn.gameObject).onClick+=OnbtnClick;
NetMgr.instance.StartClient();
NetMgr.instance.ReceiveMsg();
}
private
void
OnbtnClick(GameObject go)
{
string
msg = input.value;
if
(!
string
.IsNullOrEmpty(msg))
{
NetMgr.instance.SendMsg(NetMgr.instance.client+"说:"+msg);
}
}
void
Update
()
{
if
(NetMgr.instance.queue.Count>0)
//队列大于0
{
list.Add(NetMgr.instance.queue.Dequeue());//出队
}
}
}