c#服务器, 和Unity端 C#实现异步交互

public class StateObject
{
    //聊天用的数据
    public Socket workSocket = null;
    public const int BufferSize = 1024;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}


服务器:


using System;  
using System.CodeDom;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Sockets;  
using System.Text;  
using System.Threading;  
using System.Threading.Tasks;  
  
namespace socketAsyncCallback  
{  
      
    public class StateObject  
    {  
        public Socket WorkSocket = null;  
        public const int  BufferSize = 1024;  
        public byte[] buffer = new byte[BufferSize];  
        public StringBuilder sb = new StringBuilder();  
    }  
  
    class Program  
    {  
        public static ManualResetEvent allDone = new ManualResetEvent(false);  
        private static Socket listener;  
        static void Main(string[] args)  
        {  
            StartListening();  
              
        }  
  
        public static void StartListening()  
        {  
            byte[] bytes = new byte[1024];  
              
            IPAddress ipAddress = IPAddress.Parse("10.2.226.14");  
            int port = 8885;  
            IPEndPoint point = new IPEndPoint(ipAddress, port);  
  
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
              
            try  
            {  
                listener.Bind(point);  
                listener.Listen(10);  
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);  
                //这里本来是在这里启动一个begin的,我把他挪到了AcceptCallback方法里,这样就不用让主线程等待了  
                /* 
                while (true) 
                { 
                    allDone.Reset(); 
 
                    Console.WriteLine("Waiting fo a connection..."); 
 
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); 
 
                    allDone.WaitOne(); 
                } 
                 */  
  
            }  
            catch (Exception e)  
            {  
                Console.WriteLine(e.ToString());  
                  
            }  
  
            Console.WriteLine("\n Press Enter to continue");  
            Console.Read();  
  
  
        }  
  
        public static void AcceptCallback(IAsyncResult ar)  
        {  
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);  
            Console.WriteLine("come in AcceptCallback");  
            //allDone.Set();  
  
            Socket myListener = (Socket) ar.AsyncState;  
            Socket handler = myListener.EndAccept(ar);  
            //握手,因为我这里用来连接进来的client 是用的同步的,所以一定要握手才可以,我连接就是用的前面的一篇 socketClient的文章  
            //handler.Send(Encoding.ASCII.GetBytes("server say hello"));  
            //这里是申创造一个容器, 来传递socket  
            StateObject state = new StateObject();  
            state.WorkSocket = handler;  
            handler.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReadCallback), state);  
        }  
  
        public static void ReadCallback(IAsyncResult ar)  
        {  
              
            string content = string.Empty;  
            Console.WriteLine("READCALLBACK");  
            StateObject state = (StateObject) ar.AsyncState;  
            Socket handler = state.WorkSocket;

            //handler.Send(Encoding.ASCII.GetBytes("server say hello"));  

            int bytesRead = handler.EndReceive(ar);  
            if (bytesRead > 0)  
            {  
                Console.WriteLine(handler + ":" +Encoding.ASCII.GetString(state.buffer, 0, bytesRead));  
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));  
  
                content = state.sb.ToString();  
                //Console.WriteLine(content);  
                if (content.IndexOf("<EOF>") > -1)  
                {  
                    Console.WriteLine("Read {0} bytes from socket. \n Data: {1}",content.Length, content);  
                    //给客户端响应,这里也可以注释掉,没有关系  
                    Send(handler, content);  
                }  
                else  
                {  
                    handler.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReadCallback),  
                        state);  
                }  
            }  
        }  
  
        private static void Send(Socket handler, string data)  
        {  
            byte[] byteData = Encoding.ASCII.GetBytes(data);  
  
            handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);  
        }  
        private static void SendCallback(IAsyncResult ar)  
        {  
            try  
            {  
                Socket handler = (Socket) ar.AsyncState;  
  
                int bytesSend = handler.EndSend(ar);  
                Console.WriteLine("Send {0} bytes to client.", bytesSend);  
                handler.Shutdown(SocketShutdown.Both);  
                handler.Close();  
  
            }  
            catch (Exception e)   
            {  
                Console.WriteLine(e.ToString());  
                 
            }  
        }  
    }  
}  




客户端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using System.Collections;

public class OprationModelGUI : MonoBehaviour {

	// Use this for initialization
    private Vector2 scrollViewPosition = new Vector2(0, 5);
    private string sendMessage = "";
    private string boxMessage = "";
    private Socket clientSocket;
    private Thread reveiveThread;   //开启线程,来接收消息

	void Start () {
	    StartTalk();
        Receive(clientSocket);
        
	}
	
	// Update is called once per frame
	void Update () {
	   
	}

    void OnGUI()
    {
        //Debug.Log("testModel");
        //GUILayout.Button("ddd");

        GUILayout.Space(300);
        GUILayout.BeginVertical();
        scrollViewPosition = GUILayout.BeginScrollView(scrollViewPosition, GUILayout.Height(120), GUILayout.Width(210));
        GUILayout.Box(boxMessage);
        GUILayout.EndScrollView();

        GUILayout.BeginHorizontal();
        sendMessage = GUILayout.TextField(sendMessage,GUILayout.Width(150));
        if (GUILayout.Button("发送", GUILayout.Width(50)))
        {
            boxMessage += "\n" + "我说:" + sendMessage;
            Send(clientSocket, sendMessage);
            
            sendMessage = "";
        }
        GUILayout.EndHorizontal();

        GUILayout.EndVertical();

        
    }

    void StartTalk()
    {
        IPAddress ipAddress = IPAddress.Parse("10.2.226.14");
        int port = 8885;
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //与目标终端连接
        clientSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), clientSocket);
        //等待,直到连接程序完成, 在ConnectCallback中适当位置有connectDone.Set()
        
        //发送数据到远程终端
        //Send(client, "this is a test");
        
        //client.Shutdown(SocketShutdown.Both);
        //client.Close();
    }

    //连接部分 Callback
    void ConnectCallback(IAsyncResult ar)
    {
        //获取socket
        Socket client = (Socket) ar.AsyncState;
        //完成连接
        client.EndConnect(ar);


    }
    //数据接收

    void Receive(Socket client)
    {
        //构造容器
        StateObject state = new StateObject();
        state.workSocket = client;

        //从远程接收数据
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    }

    void ReceiveCallback(IAsyncResult ar)
    {
        Debug.Log("ReceiveCallBack");
        StateObject state = (StateObject) ar.AsyncState;
        Socket client = state.workSocket;
        
        //从远程设备读取数据
        int bytesRead = client.EndReceive(ar);
        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            
            //继续读取
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        
            
        }
        else
        {
            Debug.Log("最后没有进来");
            if (state.sb.Length > 1)
            {
                Debug.Log(state.sb.ToString());
                boxMessage += "\n" + state.sb.ToString();
            }
        }
        boxMessage += "\n" + state.sb;
    }
    
    //数据发送
    void Send(Socket client, string data)
    {
        //格式转换
        byte[] byteData = Encoding.ASCII.GetBytes(data);
        //开始发送数据到远程设备
        client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
    }

    void SendCallback(IAsyncResult ar)
    {
        Socket client = (Socket) ar.AsyncState;
        //完成数据发送
        int bytesSent = client.EndSend(ar);

    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值