UWP的Tcp套接字程序

时间:2017-08-03 16:13:22

标签: c# sockets unity3d uwp tcplistener

我正在以统一方式创建一个胶囊游戏对象,我编写了一个TCP套接字程序来连接python脚本。只要它为PC / Linux目标运行,代码就可以正常工作。但是当我尝试使用Universal 10 / D3D构建设置为UWP应用程序构建它时,它会给出编译错误,即找不到TcpListener类。我尝试使用comipler#if- #else语句解决这个问题,但由于我是UWP编程和API的新手,因此在如何将现有代码转换为使用UWP API时遇到很多麻烦。

请建议我的代码中所需的更改或一些简单的解决方法。 守则:

using System;
using UnityEngine;
using System.Collections;
// Required for socket programming
using System.IO;

#if NETFX_CORE
using Windows.Networking.Sockets;
#else
using System.Net;
using System.Net.Sockets;
#endif

using System.Text;

public class capsule : MonoBehaviour {

    public left lft;
    public right rht;


    IPAddress ipAd = IPAddress.Parse("127.0.0.1");

    #if NETFX_CORE
        Windows.Networking.Sockets.StreamSocketListener myList = new Windows.Networking.Sockets.StreamSocketListener();
    #else
        TcpListener myList;
    #endif

    #if NETFX_CORE
        Windows.Networking.Sockets.StreamSocket s = new Windows.Networking.Sockets.StreamSocket();
    #else
        Socket s;
    #endif

    byte[] b = new byte[100];
    ASCIIEncoding asen = new ASCIIEncoding();
    String str_msgs, str_cmd, str_val;


    // Use this for initialization
    void Start () {

        #if NETFX_CORE
            Debug.Log("The server is running at port 3085..." + Environment.NewLine);

            Debug.Log("Waiting for a connection..." + Environment.NewLine);

            await s.ConnectAsync(ipAd, 3085)
        #else
            myList = new TcpListener(ipAd, 3085);
            myList.Start();

            Debug.Log("The server is running at port 3085..." + Environment.NewLine);

            Debug.Log("The local End point is  :" + myList.LocalEndpoint + Environment.NewLine);

            Debug.Log("Waiting for a connection..." + Environment.NewLine);

            s = myList.AcceptSocket();

        #endif

        Debug.Log("Connection accepted " + s.RemoteEndPoint + Environment.NewLine);

        #if NETFX_CORE

            // To do something

        #else

            int k = s.Receive(b);

            Debug.Log("Recieved..." + Environment.NewLine);

            str_msgs = Encoding.UTF8.GetString(b);

            Array.Clear(b, 0, b.Length);

            Debug.Log(str_msgs + Environment.NewLine);

            s.Send(asen.GetBytes("Sent: Connected with server." + Environment.NewLine));

            Debug.Log(Environment.NewLine + "Sent Acknowledgement !" + Environment.NewLine);
        #endif
    }

我如何使用UWP接受套接字连接,并按照我使用套接字类的方式发送和接收数据。这里附有错误的屏幕截图,我在构建期间获得了该错误。

Build Error Image

0 个答案:

没有答案