TCP发送多条消息而不关闭连接

时间:2016-05-16 20:34:11

标签: c# android sockets tcp win-universal-app

大家好我已经构建了一个Android应用程序以获得GPS协调,我想通过TCP将数据发送到我的C#UWP服务器。作为概念,我打开了一个套接字,我希望在不关闭套接字的情况下发送多条消息。

socket = new java.net.Socket("192.168.2.10", 9999);
printwriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
printwriter.println("message1");
printwriter.println("message2");
printwriter.println("message3");
printwriter.println("message4");
printwriter.flush();

问题是我只接收服务器上的message1或者有时也接收messages2。另一条消息未显示在服务器上。我不想建立新连接,因为我计划发送大量消息。如果你们中的任何人知道解决方案将不胜感激。

我目前正在https://msdn.microsoft.com/en-us/windows/uwp/networking/sockets使用C#中的UWP服务器代码。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Maps
{

    class Connection
    {
        public async void Connectie()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Waiting for connection................");

                //Create a StreamSocketListener to start listening for TCP connections.
                Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();

                //Hook up an event handler to call when connections are received.
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                //Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use.
                await socketListener.BindServiceNameAsync("9999");
                System.Diagnostics.Debug.WriteLine("Waiting for connection................");
            }
            catch (Exception e)
            {
                //Handle exception.
            }
        }

        private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
    Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Stream inStream = args.Socket.InputStream.AsStreamForRead();
            StreamReader reader = new StreamReader(inStream);
                reader = new StreamReader(args.Socket.InputStream.AsStreamForRead());
                System.Diagnostics.Debug.WriteLine("connection................");
                //Read line from the remote client.
                string request = await reader.ReadLineAsync();
                System.Diagnostics.Debug.WriteLine(request);                 
         }
    }
}

2 个答案:

答案 0 :(得分:0)

您的服务器代码不正确,您必须继续阅读SocketListener_ConnectionReceived,直到没有任何内容可读,但在这里您只读一行,请考虑添加while循环。这种循环有很多例子,例如here

答案 1 :(得分:0)

除了@Hasson关于阅读所有行的内容之外,你应该确保你正确处理了流(最好在StreamReader上使用,你可以在Stream上做同样的事情,尽管StreamReader配置也将关闭它)。看起来您的代码希望在一次调用中获取整个消息,因此如果您不想在每个ReadLineAsync之前使用while循环检查!reader.EndOfStream,您可以执行以下操作:

using (Stream inStream = args.Socket.InputStream.AsStreamForRead())
using (StreamReader reader = new StreamReader(inStream))
{
    System.Diagnostics.Debug.WriteLine("connection................");
    //Read line from the remote client.
    string request = await reader.ReadToEndAsync();
    System.Diagnostics.Debug.WriteLine(request);  
}

我也有点担心这门课程的用法。如果实例化一个新的Connection()的代码没有保持对它的引用可用,那么垃圾收集器将吞没它,你的服务器将不再监听。

例如,如果您点击按钮或加载页面,请执行以下操作:

Connection conn = new Connection();
conn.Connectie();

如果没有对conn维护的引用,那么在调用该函数之后,垃圾收集器将自动处理它和你的StreamSocketListener。