我有一台客户端 PC 使用我编写的 TCP_client 程序通过 TCP 向我发送数据。基本上,我正在向服务器发送一条“Hello Message”。
class Program
{
const int ourPort = 9090;
static IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.10"), 3000);
static ASCIIEncoding encoder = new ASCIIEncoding();
static System.Timers.Timer aTimer;
static void Main(string[] args)
{
aTimer = new System.Timers.Timer(200);
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;
Console.Read();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
try
{
TcpClient client = new TcpClient();
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
catch (Exception ee)
{
Console.WriteLine(ee.ToString());
}
}
我正在使用我的 PC 使用我编写的 TCP_server 程序接收该数据。
class Server
{
private static TcpListener tcpListener;
static System.Timers.Timer aTimer;
static int count = 0;
public Server()
{
//
}
static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 3000);
tcpListener.Start();
aTimer = new System.Timers.Timer(200);
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;
Console.Read();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
TcpClient client = tcpListener.AcceptTcpClient();
Thread.Sleep(2);
NetworkStream clientStream = client.GetStream();
Thread.Sleep(2);
byte[] message = new byte[4096];
int bytesRead;
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
client.Close();
}
catch (Exception ee)
{
Console.WriteLine("socket error");
Console.WriteLine(ee.ToString());
client.Close();
}
if (bytesRead == 0)
{
client.Close();
}
count++;
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(count + " " + encoder.GetString(message, 0, bytesRead));
}
总而言之,我遇到的问题是,我偶尔会在 TCP_server 程序的 Catch() 中遇到“套接字错误”。
错误:
System.IO.IOException: Unable to read data from the transport connection: An exi sting connection was forcibly closed by the remote host. ---> System.Net.Sockets .SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s ize) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s ize) at test_tcp_manager.Server.OnTimedEvent(Object source, ElapsedEventArgs e) in c:\Users\user\Documents\Visual Studio 2012\Projects\test_tcp_manager\test_tcp_ma nager\Program.cs:line 52
错误不规律地出现一秒或几秒。我想知道为什么,我想知道如何解决这个问题。
U**来自用户输入的修复** 来自用户 Usr 反馈的第一个代码修复:
tcp_client 代码现在看起来像这样:
class Program
{
const int ourPort = 9090;
static IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("172.22.1.22"), 3000);
static ASCIIEncoding encoder = new ASCIIEncoding();
static void Main(string[] args)
{
while (true)
{
try
{
using( TcpClient client = new TcpClient())
{
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0, buffer.Length);
client.Close();
}
}
catch (Exception ee)
{
Console.WriteLine(ee.ToString());
}
}
}
}
tcp_server 代码现在看起来像这样:
class Server
{
private static TcpListener tcpListener;
static int count = 0;
public Server()
{
//
}
static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 3000);
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
byte[] message = new byte[4096];
int bytesRead;
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ee)
{
Console.WriteLine("Socket rror");
Console.WriteLine(ee.ToString());
}
count++;
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine(count + " " + encoder.GetString(message, 0, bytesRead));
}
}
}
最佳答案
很多问题。套接字编程很难。非常小心。
关于c# - TCP 连接断开/或无法通过 TCP 接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24765531/
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是