using UnityEngine; using System.Net.Sockets; using System;
using System.Collections.Generic; using UnityEngine.UI; using System.Collections;
public class ChatClient : MonoBehaviour { public GameObject content; public InputField input; //用于发送输入框的信息 public InputField usernameInput;//客户端用户名 public GameObject messageItem;//预制件的宽高 public Button connectButton; //连接按钮
TcpClient client;//客户端 NetworkStream nstream;//网络数据流 string ip = "192.168.10.5";//客户端IP int port = 10086;//客户端端口 byte[] data;//客户端收发数据 bool isCOnnect= false;
List messageList;//存储接受的消息列表 public int messagesMaxSize = 20;//存储接受的消息列表最大长度 bool isNewMessage = false;//消息更新的标志位 string newMessage;//接受到的最新信息 //预制件的宽高 float height = 0; float width = 0; void Start() { messageList = new List(); messageList.Capacity = messagesMaxSize;
//初始化组件 if (cOntent== null) cOntent= transform.FindChild("Chat View/Viewport/Content").gameObject; if (input == null) input = transform.FindChild("InputField").GetComponent(); if (usernameInput == null) usernameInput = transform.FindChild("UsernameInput").GetComponent();
if (cOnnectButton== null) cOnnectButton= transform.FindChild("ConnectButton").GetComponent
简单的负责debug的提示信息类
using UnityEngine; using System.Collections;
public class Info : MonoBehaviour {
public static string debugStr = "";
void OnGUI() { GUILayout.Label(debugStr);
} }
服务器端的代码
主程序
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks;
namespace ChatSystem { class Program { static void Main(string[] args) { //设置监听的端口号 Console.WriteLine("请输入服务器需要监听的端口: "); string input = Console.ReadLine(); int port = int.Parse(input); //调用方法启动服务器 Server(port); }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Net; using System.Text; using System.Threading.Tasks; using System.Collections;
namespace ChatSystem { class ChatServerHandle { public static Hashtable Clients = new Hashtable();//客户端连接记录表 public TcpClient client;//客户端 public string username;//客户端用户名
public string ip;//客户端IP public int port;//客户端端口
public byte[] data;//客户端收发数据
bool firstCOnnet= true;
public ChatServerHandle(TcpClient client) { this.client = client;