目录
1、打开 VS 2017 ,新建一个控制台程序,具体如下图
2、 服务端 Main 程序
3、Unity 实现客户端代码
4、运行效果
在 Unity 和 VS 2017 ,使用C#开发简单的聊天程序,包括服务端和客服端。
using System;
using System.Net.Sockets;
namespace TestServer_XAN
{
class Program
{
// 设置连接端口
const int portNo = 500;
///
/// 聊天服务程序入口
///
///
static void Main(string[] args)
{
// 服务器地址(根据自己的需要填写)
System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("127.0.0.1");
// 绑定 IP 和端口号 开始监听客端户接入
TcpListener listener = new TcpListener(localAdd,portNo);
listener.Start();
Console.WriteLine("Server is Starting...\n");
// 死循环监听客户端连接服务器
while (true) {
ChatClient user = new ChatClient(listener.AcceptTcpClient());
Console.WriteLine(user._clientIP + " is joined...\n");
}
}
}
}
using System;
using System.Collections;
using System.Net.Sockets;
namespace TestServer_XAN
{
public class ChatClient
{
///
/// 客户端的集合
///
public static Hashtable AllClients = new Hashtable();
///
/// Tcp 客户端
///
private TcpClient _client;
///
/// 客户端 IP
///
public string _clientIP;
///
/// 客户端昵称
///
private string _clientNickname;
///
/// 客户端数据
///
private byte[] data;
///
/// 客户端连接的第一次
///
private bool ReceiveNick = true;
///
/// 构造函数u,初始化数据,并且绑定事件
///
///
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._clientNickname + " has left the chat");
return;
}
else {
string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
// 连接服务器的时候
if (ReceiveNick)
{
this._clientNickname = messageReceived;
Broadcast(this._clientNickname + ">" + messageReceived);
ReceiveNick = false;
}
else {
Broadcast(this._clientNickname + ">" + 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._clientNickname + "has left ths chat.");
}
}
///
/// 发送消息
///
///
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);
}
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
public class ClientHandler : MonoBehaviour
{
const int portNo = 500;
private TcpClient _client;
byte[] data;
public string nickName = "";
public string message = "";
public string sendMsg = "";
///
/// UI界面
///
void OnGUI() {
nickName = GUI.TextField(new Rect(10,10,100,20),nickName);
message = GUI.TextField(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),"connect")) {
Connect();
}
if (GUI.Button(new Rect(230,250,80,20), "Send")) {
Send();
}
}
///
/// 连接服务器
///
public void Connect() {
//服务器的IP和端口号
this._client = new TcpClient("127.0.0.1",portNo);
data = new byte[this._client.ReceiveBufferSize];
SendMessage(nickName);
this._client.GetStream().BeginRead(data,0,System.Convert.ToInt32(this._client.ReceiveBufferSize), ReceiveMessage, null);
}
///
/// 发送
///
private void Send() {
SendMessage(sendMsg);
sendMsg = "";
}
///
/// 发送消息
///
///
public void SendMessage(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 {
Debug.Log(System.Text.Encoding.ASCII.GetString(data,0,bytesRead));
message += System.Text.Encoding.ASCII.GetString(data,0,bytesRead);
}
this._client.GetStream().BeginRead(data,0,System.Convert.ToInt32(this._client.ReceiveBufferSize),ReceiveMessage, null);
}
catch (System.Exception ex)
{
}
}
}