1- 我有一个 GHIElectronics FEZ Spider 3 设备
2- 我已经通过以太网电缆将设备连接到我的笔记本电脑并配置了网络设置
3- 我可以使用 cmd 从笔记本电脑 ping FEZ 设备:ping 172.16.43.193
4- 我已经编写了一个 Windows 窗体应用程序在我的笔记本电脑上运行并充当 TCP 接收器
5- 我想从 FEZ 设备发送 TCP 数据包到我笔记本电脑上的 win 应用程序
以下是win应用代码:
string[] dnsAddresses = { "172.16.40.2", "172.16.40.5" };
const Int32 c_port = 12250;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
System.Threading.Thread t = new Thread(new ThreadStart(SendTCPMessage));
txtStatus.Text = txtStatus.Text + "TCP listening established successfully\r\n";
}
catch (Exception ex)
{
txtStatus.Text = txtStatus.Text + "An error occured while trying to establish TCP listening : \r\n" + ex.Message + "\r\n";
if (ex.InnerException != null)
txtStatus.Text = txtStatus.Text + ex.InnerException + "\r\n";
}
}
private void SendTCPMessage()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, c_port);
server.Bind(localEndPoint);
server.Listen(1);
while (true)
{
// Wait for a client to connect.
Socket clientSocket = server.Accept();
// Process the client request. true means asynchronous.
new ProcessClientRequest(clientSocket, true);
}
}
internal sealed class ProcessClientRequest
{
private Socket m_clientSocket;
/// <summary>
/// The constructor calls another method to handle the request, but can
/// optionally do so in a new thread.
/// </summary>
/// /// <param name="clientSocket"></param>
/// <param name="asynchronously"></param>
public ProcessClientRequest(Socket clientSocket, Boolean asynchronously)
{
m_clientSocket = clientSocket;
if (asynchronously)
// Spawn a new thread to handle the request.
new Thread(ProcessRequest).Start();
else ProcessRequest();
}
/// <summary>
/// Processes the request.
/// </summary>
private void ProcessRequest()
{
const Int32 c_microsecondsPerSecond = 1000000;
// 'using' ensures that the client's socket gets closed.
using (m_clientSocket)
{
// Wait for the client request to start to arrive.
Byte[] buffer = new Byte[1024];
if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
SelectMode.SelectRead))
{
// If 0 bytes in buffer, then the connection has been closed,
// reset, or terminated.
if (m_clientSocket.Available == 0)
return;
// Read the first chunk of the request (we don't actually do
// anything with it).
Int32 bytesRead = m_clientSocket.Receive(buffer,
m_clientSocket.Available, SocketFlags.None);
String result = "";
string FileContent = new string(Encoding.UTF8.GetChars(buffer));
MessageBox.Show("Text file with following content received :\r\n" + FileContent);
if (SaveFile(FileContent))
{
result = "1";
}
else
{
result = "0";
}
// Return a static string to the client.
byte[] buf = Encoding.UTF8.GetBytes(result);
int offset = 0;
int ret = 0;
int len = buf.Length;
while (len > 0)
{
ret = m_clientSocket.Send(buf, offset, len, SocketFlags.None);
len -= ret;
offset += ret;
}
m_clientSocket.Close();
}
}
}
private bool SaveFile(string FileContent)
{
bool returnValue = false;
try
{
string RootSaveDirectory = ConfigurationManager.AppSettings["FileSaveRootDirectory"].ToString();
string SaveDirectoryName = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + " " + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString();
string SaveDirectory = Path.Combine(RootSaveDirectory, SaveDirectoryName);
if (!Directory.Exists(SaveDirectory))
{
Directory.CreateDirectory(SaveDirectory);
}
string FileName = ConfigurationManager.AppSettings["FileName"].ToString();
File.WriteAllText(Path.Combine(SaveDirectory, FileName), FileContent);
returnValue = true;
}
catch { }
return returnValue;
}
}
以下是我在 FEZ 设备上用于将 TCP 数据包发送到笔记本电脑上的 win 应用程序的代码:
public bool SendFile()
{
bool returnValue = false;
try
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ServerIP = new IPAddress(new byte[] { 172, 16, 43, 193 });
IPEndPoint ServerEndPoint = new IPEndPoint(ServerIP, 12250);
byte[] buf = Encoding.UTF8.GetBytes(FileContentText);
socket.Connect(ServerEndPoint);
socket.Send(buf);
if (socket.Poll(5 * 1000000, SelectMode.SelectRead)) // wait for data from the server
{
byte[] inbuf = new byte[socket.Available];
socket.Receive(inbuf);
//string m = new string(Encoding.UTF8.GetChars(inbuf));
}
socket.Close();
}
catch (SocketException ex)
{
string s = ex.Message;
if (ex.InnerException != null)
s = s + ex.InnerException.Message;
if (ex.StackTrace != null)
s = s + ex.StackTrace;
}
return returnValue;
}
问题是在 FEZ 设备上,当我尝试在以下代码行发送 tcp 数据包时
socket.Connect(ServerEndPoint);
抛出具有以下 Id 的 SocketException :
10054
最佳答案
我假设在你的情况下 socket.Poll() 在数据到达之前立即返回 false,当它离开 using block 的范围时关闭套接字。
如果我的假设是正确的,我会重写 ProcessRequest 方法 - 跳过 Poll() 和 Socket.Available 检查,并且只需使用 socket.Receive()。
socket.Receive() 将阻塞(您的工作线程)直到它收到响应,如果远程方已断开连接则返回 0。
类似于:
using (m_clientSocket)
{
int bytes;
while ((bytes = m_clientSocket.Receive(...)) > 0)
{
// process "bytes" bytes from the buffer
}
// other side has disconnected
}
并且不要忘记在该例程中捕获 SocketException。
关于c# - 尝试 socket.Connect 时出现 Socket Exception 10054,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814081/
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
我正在使用Postgres.app在OSX(10.8.3)上。我已经修改了我的PATH,以便应用程序的bin文件夹位于所有其他文件夹之前。Rammy:~phrogz$whichpg_config/Applications/Postgres.app/Contents/MacOS/bin/pg_config我已经安装了rvm并且可以毫无错误地安装pggem,但是当我需要它时我得到一个错误:Rammy:~phrogz$gem-v1.8.25Rammy:~phrogz$geminstallpgFetching:pg-0.15.1.gem(100%)Buildingnativeextension
我最近对我的计算机(OS-MacOSX10.6.8)进行了删除,并且我正在重新安装我所有的开发工具。我再次安装了RVM;但是,它不会让我安装Ruby1.9.3。到目前为止我已经尝试过:rvminstall1.9.3rvm安装1.9.3-p194rvm安装1.9.3-p448rvminstall1.9.3--with-gcc=clang所有返回相同的命令行错误:Searchingforbinaryrubies,thismighttakesometime.Nobinaryrubiesavailablefor:osx/10.6/x86_64/ruby-1.9.3-p448.Continuin