python socket立即发送

时间:2015-08-05 08:04:43

标签: python sockets

套接字的问题在于它们缓冲数据并在缓冲区填充时或在给定间隔内发送它。有什么办法可以避免它并通过高优先级的套接字发送一些东西,没有任何延迟?在我的情况下,毫秒计数。

1 个答案:

答案 0 :(得分:5)

TCP_NODELAY是您正在寻找的选项

示例代码:

 FileStream fileStream = System.IO.File.OpenRead(Server.MapPath("/10002_en.flac"));
                MemoryStream memoryStream = new MemoryStream();
                memoryStream.SetLength(fileStream.Length);
                fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
                byte[] BA_AudioFile = memoryStream.GetBuffer();
                HttpWebRequest _HWR_SpeechToText = null;
                _HWR_SpeechToText = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=my-key");
                _HWR_SpeechToText.Credentials = CredentialCache.DefaultCredentials;
                _HWR_SpeechToText.Method = "POST";
                _HWR_SpeechToText.ContentType = "audio/x-flac; rate=44100";
                _HWR_SpeechToText.ContentLength = BA_AudioFile.Length;
                Stream stream = _HWR_SpeechToText.GetRequestStream();
                stream.Write(BA_AudioFile, 0, BA_AudioFile.Length);
                stream.Close();
                HttpWebResponse HWR_Response = (HttpWebResponse)_HWR_SpeechToText.GetResponse();

                StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
                string responseFromServer = (SR_Response.ReadToEnd());

                String[] jsons = responseFromServer.Split('\n');

有关详细信息,请参阅

this SO QA

this article

this other SO QA

注意:在Linux系统上,选项TCP_CORK也可用。

在您的应用程序中试用这两个选项,看看会发生什么。 请阅读this exhaustive and very informative article关于两者的优缺点。