进程之间简单Socket通信

当两个应用要嵌套的时候,嵌套完成之后需要通信,比如Unity和WF的通信,我试过NamedPipeServerStream这种命名管道,但是由于Unity只能使用.Net2.0。所以但Unity给WF发消息的时候出现bug(打断点后,Unity卡死),无法正常发送。
Unity端做客户端

public abstract class BasicSocket

{

    public event EventHandler<SocketEventArgs> DataReceived;

    public const string DEFAULT_HOST = "127.0.0.1";

    public const int DEFAULT_PORT = 8888;

    protected string _host;

    protected int _port;

    protected int _bufferSize;

    protecte TcpClient _client;

    protected Thread _receiveThread;

    protected virtual void Receive()

    {

        while(true)

        {

            if(_client.Available<0)

            {

                Thread.Sleep(100);

                Continue;

            }

            var datas = new byte[_bufferSize_];

            var stream = _client.GetStream();

            var readed = stream.Read(datas,0,datas.Length);

            PopData(Encoding.UTF8.GetString(datas,0,readed);

        }

    }

    protected void PopData(string str)

    {

        DataReceived?.Invoke(this,new SocketEventArgs(str));

    }

    public void Send(string data)

    {

        var datas = Encoding.UTF8.GetBytes(data);

        var stream = _client.GetStream();

        stream.Write(datas,0,datas.Length);

        stream.Fluse();

    }

    public void Close()

    {

        _client?.Close();

        _threadReceive?.Abrot();

    }

    

}



public class SocketEventArgs:EventArgs

{

    public string String {get; protected set;}

    public SocketEventArgs(stirng str)

    {

        String  = str;

    }

}


public classs ClientSocket:BaseSocket

{

    public ClientSocket():this(DEFAUTL_HOST,DEFAULT_PORT)

    public ClientSocket(string host,int port)

    {

        _host = host;

        _port = port;

        _client = new TcpClinet();

        _bufferSize = _client.ReceivedBufferSize;

        _receiveThread = new Thread(Receive);

    }


    public void Connect()

    {

        _client.Connect(_host,_port);

        _receiveThread.Start();

    }

}


public class ServerSocket:BasicSocket

{

    private readonly TcpListener _tcpListener;

    private readonly Tread _connectTread;

    

    public ServerSocket():this(DEFAULT_HOST,DEFAULT_PORT){}

    public ServerSocket(string host ,int port)

    {

        _tcpListener = new TcpListener(IPAddress.Parse(host),port);

        _bufferSize = _tcpListener.Server.ReceiveBufferSize;

        _connectTread = new Thread(WaitConnect);

    }


    public void Start()

    {

        _tcpListener.Start();

        _connectTread .Start();

    }

    private void WaitConnect()

    {

        _client = _tcpListener.AcceptTcpClinet();

        _receiveThread = new Thread(Receive);

        _receiveThread.Start();

    }

    public override void Close()

    {

        _tcpListener.Stop();

        _connectThread.Abort();

        base.Close();

    }



}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页