本文主要是介绍Unity3D网络之Socket聊天室初探,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先创建一个服务端程序,这个程序就用VS的控制台程序做就行了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace SocketServer
{
class Program
{
const int Port = 20000; //设置连接端口
static void Main(string[] args)
{
// 初始化服务器IP
System.Net.IPAddress SocketIP = System.Net.IPAddress.Parse("127.0.0.1");
// 创建TCP侦听器
TcpListener listener = new TcpListener(SocketIP, Port);
listener.Start();
// 显示服务器启动信息
Console.WriteLine("服务开启中...\n");
// 循环接受客户端的连接请求
while (true)
{
ChatClient client = new ChatClient(listener.AcceptTcpClient());
// 显示连接客户端的IP与端口
Console.WriteLine(client._clientIP + " 加入...\n");
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net.Sockets;
namespace SocketServer
{
class ChatClient
{
public static Hashtable ALLClients = new Hashtable(); // 客户列表
private TcpClient _client; // 客户端实体
public string _clientIP; // 客户端IP
private string _clientNick; // 客户端昵称
private byte[] data; // 消息数据
private bool ReceiveNick = true;
public ChatClient(TcpClient client)
{
this._client = client;
this._clientIP = client.Client.RemoteEndPoint.ToString();
// 把当前客户端实例添加到客户列表当中
ALLClients.Add(this._clientIP, this);
data = new byte[this._client.ReceiveBufferSize];
// 从服务端获取消息
client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
}
// 从客戶端获取消息
public void ReceiveMessage(IAsyncResult ar)
{
int bytesRead;
try
{
lock (this._client.GetStream())
{
bytesRead = this._client.GetStream().EndRead(ar);
}
if (bytesRead < 1)
{
ALLClients.Remove(this._clientIP);
Broadcast(this._clientNick + "离开聊天室");
return;
}
else
{
string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
if (ReceiveNick)
{
this._clientNick = messageReceived;
Broadcast(this._clientNick + "加入聊天室");
ReceiveNick = false;
}
else
{
Broadcast(this._clientNick + ":" + messageReceived);
}
}
lock (this._client.GetStream())
{
this._client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
}
}
catch (Exception ex)
{
ALLClients.Remove(this._clientIP);
Broadcast(this._clientNick + "离开聊天室");
}
}
// 向客戶端发送消息
public void sendMessage(string message)
{
try
{
System.Net.Sockets.NetworkStream ns;
lock (this._client.GetStream())
{
ns = this._client.GetStream();
}
// 对信息进行编码
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
ns.Write(bytesToSend, 0, bytesToSend.Length);
ns.Flush();
}
catch (Exception ex)
{
}
}
// 向客户端广播消息
public void Broadcast(string message)
{
Console.WriteLine(message);
foreach (DictionaryEntry c in ALLClients)
{
((ChatClient)(c.Value)).sendMessage(message + Environment.NewLine);
}
}
}
}
这个比较简单啊,我就直接拷贝了别人的代码,比较好理解,适合新手~~~(如有侵犯版权,请私信联系我)
接下来就是Unity这边的代码了~
代码如下:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net.Sockets;
public class ScoketClient : MonoBehaviour
{
const int Port = 20000;//端口号与服务端端口对应
private TcpClient client;
byte[] data;
public string UserName = "";//用户名
public string message = "";//聊天内容
public string sendMsg = "";//输入框
void OnGUI()
{
UserName = GUI.TextField(new Rect(10, 10, 100, 20), UserName);
message = GUI.TextArea(new Rect(10, 40, 300, 200), message);
sendMsg = GUI.TextField(new Rect(10, 250, 210, 20), sendMsg);
if (GUI.Button(new Rect(120, 10, 80, 20), "连接服务器"))
{
this.client = new TcpClient();
this.client.Connect("127.0.0.1", Port);
data = new byte[this.client.ReceiveBufferSize];
SendSocket(UserName);
this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
};
if (GUI.Button(new Rect(230, 250, 80, 20), "发送"))
{
SendSocket(sendMsg);
sendMsg = "";
};
}
public void SendSocket(string message)
{
try
{
NetworkStream ns = this.client.GetStream();
byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
ns.Write(data, 0, data.Length);
ns.Flush();
}
catch (Exception ex)
{
}
}
public void ReceiveMessage(IAsyncResult ar)
{
try
{
int bytesRead;
bytesRead = this.client.GetStream().EndRead(ar);
if (bytesRead < 1)
{
return;
}
else
{
message += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
}
this.client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(this.client.ReceiveBufferSize), ReceiveMessage, null);
}
catch (Exception ex)
{
}
}
}
这样就可以了~先开启服务端,然后在用客户端连接。这里用的编码是ASCII。如果想用中文的话改成UTF-8,或者GB2312。
这篇关于Unity3D网络之Socket聊天室初探的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!