C#socket编程_TCPunity聊天室.02

上篇写完服务端的代码,可以接收一条数据,其实只要在原代码上加个线程,线程里加个死循环,一直接收数据,当socket断开后再跳出即可,接下来写客户端的代码,客户端代码也是差不多,1.创建socket,2.连接服务端,3.接收发送消息

首先在unity上搭建聊天室框架,这里用到了NGUI插件,不过聊天室界面怎么搭都可以,直接上代码:

    public string ipaddress = "192.xxx.xxx.x";//自己内网的IP地址
    public int port = 7788;
    public UIInput textInput;
    public UILabel chatLabel;
    private Socket clientSocket;
    private Thread t;
    private byte[]data=new byte[1024];
    private string message="";

    void Start()
    {
      ConnectToServer();
    }
    void Update()
    {
     if(message!=null&&message!="")
     {
     chatLabel.text+="\n"+message;
     message="";//清空消息
     }

    void ConnectToServer()
    {
     clientSocket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress),port));
     //创建线程
     Thread t=new Thread(ReceiveMessage);
     t.Start();
    }
    //接收消息
    void ReceiveMessage()
    {
        while (true)
        {
            if (!clientSocket.Connected)
                break;
            int length = clientSocket.Receive(data);
             message = Encoding.UTF8.GetString(data, 0, length);
            //chatLabel.text += "\n" + message;
        }
    }
    void SendMessage(string message)
    {
    byte[] data=Endcoding.UTF8.GetBytes(message);
    clientSocket.Send(data);
    }
    public void OnSendButtonClick()
    {
    string value=textInput.text;
    SendMessage(value);
    textInput.value="";
    }
    void OnDestroy()
    {
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();//关闭连接
    }
    }

你可能感兴趣的:(c#)