TCP 在不关闭连接的情况下发送多条消息 [英] TCP Send multiple message without closing connection

查看:34
本文介绍了TCP 在不关闭连接的情况下发送多条消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi guys i have build an app for android to get the GPS coordination and i want to send the data to my C# UWP server through TCP. As concept i have opened a socket and i want to send multiple messages without closing the socket.

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();

问题是我只在服务器上接收消息 1 或有时也接收消息 2.另一条消息未显示在服务器上.我不想建立新的连接,因为我打算发送很多消息.如果你们中有人知道解决方案,我们将不胜感激.

The problem is i only receive message1 or sometimes also messages2 on the server. The other message doesn't show on the server. I don't want to make new connection because i'm planning sending a lot of messages. If any of you know a solution would be appreciated.

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

I'm currently using the server code for UWP in C# from https://msdn.microsoft.com/en-us/windows/uwp/networking/sockets.

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);                 
         }
    }
}

推荐答案

除了@Hasson 所说的阅读所有行之外,您还应该确保正确处理流(最好在 StreamReader 上使用 using,并且您可以对 Stream 执行相同操作,尽管 StreamReader dispose 也会关闭它).看起来您的代码希望在一次调用中获取整个消息,因此如果您不想使用在每个 ReadLineAsync 之前检查 !reader.EndOfStream 的 while 循环,您可以执行以下操作:

In addition to what @Hasson said about reading all the lines, you should make sure that you're properly disposing the stream (preferably with a using on the StreamReader, and you could do the same on Stream, although the StreamReader dispose would close it also). It looks like your code is hoping to get the whole message in one call though, so if you don't want to use a while loop that checks !reader.EndOfStream before each ReadLineAsync, you could do something like this:

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);  
}

我也有点担心这个类的使用.如果实例化 new Connection() 的代码没有保持对它的引用可用,垃圾收集器将把它全部吞噬,您的服务器将不再监听.

I'm also a little worried about the usage of this class. If the code that instantiates a new Connection() doesn't keep a reference to it available, the garbage collector will gobble it all up and your server won't be listening anymore.

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

For example, if you're having a button click or a page load doing something like this:

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

如果没有维护对 conn 的引用,则在调用该函数后,垃圾收集器将自动处理它和您的 StreamSocketListener.

Where there isn't some reference to conn maintained, then after that function is done being called, the garbage collector will automatically dispose it and your StreamSocketListener.

这篇关于TCP 在不关闭连接的情况下发送多条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆