我們可以使用異步通信接收TCP消息。
初始化服務器套接字,並嘗試連接:
// Specify the size according to your need.
private byte[] bytData = new byte[1024 * 50000];
private Socket oServerSocket;
private void WindowLoaded(object sender, RoutedEventArgs e)
{
try
{
// We are using TCP sockets
this.oServerSocket = new Socket(
addressFamily: AddressFamily.InterNetwork,
socketType: SocketType.Stream,
protocolType: ProtocolType.Tcp);
// Assign the any IP of the hardware and listen on port number which the hardware is sending(here it's 5656)
var oIPEndPoint = new IPEndPoint(address: IPAddress.Any, port: 5656);
// Bind and listen on the given address
this.oServerSocket.Bind(localEP: oIPEndPoint);
this.oServerSocket.Listen(backlog: 4);
// Accept the incoming clients
this.oServerSocket.BeginAccept(this.OnAccept, null);
this.oLogger.WriteLog("Server started");
}
catch (Exception ex)
{
// Handle Exception
}
}
在連接成功:
private void OnAccept(IAsyncResult ar)
{
try
{
var oClientSocket = this.oServerSocket.EndAccept(asyncResult: ar);
// Start listening for more clients
this.oServerSocket.BeginAccept(callback: this.OnAccept, state: null);
// Once the client connects then start receiving the commands from her
oClientSocket.BeginReceive(
buffer: this.bytData,
offset: 0,
size: this.bytData.Length,
socketFlags: SocketFlags.None,
callback: this.OnReceive,
state: oClientSocket);
}
catch (Exception ex)
{
// Handle Exception
}
}
進程接收到的消息:
private void OnReceive(IAsyncResult ar)
{
try
{
var oClientSocket = (Socket)ar.AsyncState;
oClientSocket.EndReceive(asyncResult: ar);
/* Process the data here
BitConverter.ToInt32(value: this.bytData, startIndex: 0);
string SomeString= Encoding.ASCII.GetString(bytes: this.bytData, index: 8, count: 5);
*/
// Specify the size according to your need.
this.bytData = null;
this.bytData = new byte[1024 * 50000];
oClientSocket.BeginReceive(
buffer: this.bytData,
offset: 0,
size: this.bytData.Length,
socketFlags: SocketFlags.None,
callback: this.OnReceive,
state: oClientSocket);
}
catch (Exception ex)
{
// Handle Exception
}
}
IMHO,最廣泛使用的方法是[ WCF netTCPBinding](http://msdn.microsoft.com/en-us/library/ms731343.aspx)和[套接字](http://msdn.microsoft.com/en-us/ library/system.net.sockets.socket.aspx) – oleksii
CodeProject上有一篇名爲「完整的TCP服務器/客戶端通信和C#中的RMI框架」的文章[這裏](http://www.codeproject.com/)文章/ 155282/A-Complete-TCP-Server-Client-Communication-and-RMI)和用法是[here](http://www.codeproject.com/Articles/153938/A-Complete-TCP-Server-Client - 通信 - 和 - RMI)。在所謂的「如何編寫可擴展的基於TCP/IP的服務器」中有一個很好的問題,就是[這裏](http://stackoverflow.com/q/869744/704144)。這些鏈接對您的問題沒有確切的答案,但它們可能對您的情況有用。 –
但是這需要客戶端和服務器都使用這個框架? 我無法控制與之通信的硬件。該協議已經定義。 – magol