How to Get GPS Devices data GT06 CONCOX Protocol over TCP connection - c#

Receiving data from GPS Device:
I have a TCP server setup which is receiving data from various GPS Trackers (GT06). Each GPS devices initiates the request, server accepts it, and starts receiving NMEA data.
Problem Is when GPS Connect to Server Error:"An existing connection was forcibly closed by the remote host"
The problem is that I don't know how to receive data from GPS over GPRS/TCP connection.
Any suggestions?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace T1
{
class Program
{
public class StateObject
{
public const int DEFAULT_SIZE = 1024; //size of receive buffer
public byte[] buffer = new byte[DEFAULT_SIZE]; //receive buffer
public int dataSize = 0; //data size to be received
public bool dataSizeReceived = false; //received data size?
public StringBuilder sb = new StringBuilder(); //received data String
public int dataRecieved = 0;
public Socket workSocket = null; //client socket.
public DateTime TimeStamp; //timestamp of data
public const int BufferSize = 256;
} //end class StateObject
public static AutoResetEvent allDone = new AutoResetEvent(false);
public static AutoResetEvent acceptDone = new AutoResetEvent(false);
static void Main(string[] args)
{
StartListening();
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPAddress local = IPAddress.Parse("103.118.16.129");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8821);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// Console.WriteLine("\nPress ENTER to continue...");
// Console.Read();
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void Send(Socket handler, byte[] data)
{
// Convert the string data to byte data using ASCII encoding.
// byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(data, 0, data.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
static byte[] Unpack(string data)
{
//return null indicates an error
List<byte> bytes = new List<byte>();
// check start and end bytes
if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A"))
{
return null;
}
for (int index = 4; index < data.Length - 4; index += 2)
{
bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));
}
//crc test
byte[] packet = bytes.Take(bytes.Count - 2).ToArray();
byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();
uint CalculatedCRC = crc_bytes(packet);
return packet;
}
static public UInt16 crc_bytes(byte[] data)
{
ushort crc = 0xFFFF;
for (int i = 0; i < data.Length; i++)
{
crc ^= (ushort)(Reflect(data[i], 8) << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) > 0)
crc = (ushort)((crc << 1) ^ 0x1021);
else
crc <<= 1;
}
}
crc = Reflect(crc, 16);
crc = (ushort)~crc;
return crc;
}
static public ushort Reflect(ushort data, int size)
{
ushort output = 0;
for (int i = 0; i < size; i++)
{
int lsb = data & 0x01;
output = (ushort)((output << 1) | lsb);
data >>= 1;
}
return output;
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
if (state.buffer[3] == 1)
{
string input = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");
Console.WriteLine("Recived {0} bytes to client.", input);
//byte[] bytes = Unpack(input);
//byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();
//byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };
//serialNumber.CopyTo(response, 4);
//UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());
//response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);
//response[response.Length - 1] = (byte)((sendCRC) & 0xFF);
//Send(handler, response);
// handler.Send(response);
}
else
{
// There might be more data, so store the data received so far.
//state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
// content = state.sb.ToString();
Console.WriteLine("Recived {0} bytes to client.", Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// SaveData(content);
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
// }
}
}
}
}
}

#jdweng
Sir I try your Suggestion But Same problem Not Receiving any Message.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace T1
{
internal class Program
{
public class StateObject
{
public const int DEFAULT_SIZE = 1024; //size of receive buffer
public byte[] buffer = new byte[DEFAULT_SIZE]; //receive buffer
public int dataSize = 0; //data size to be received
public bool dataSizeReceived = false; //received data size?
public StringBuilder sb = new StringBuilder(); //received data String
public int dataRecieved = 0;
public Socket workSocket = null; //client socket.
public DateTime TimeStamp; //timestamp of data
public const int BufferSize = 256;
} //end class StateObject
public static AutoResetEvent allDone = new AutoResetEvent(false);
public static AutoResetEvent acceptDone = new AutoResetEvent(false);
private static void Main(string[] args)
{
Write_log("StartListening");
StartListening();
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8821);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
Write_log("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
Write_log("allDone");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// Console.WriteLine("\nPress ENTER to continue...");
// Console.Read();
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void Send(Socket handler, byte[] data)
{
// Convert the string data to byte data using ASCII encoding.
// byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
Write_log("ReadCallback...");
}
private static byte[] Unpack(string data)
{
//return null indicates an error
List<byte> bytes = new List<byte>();
// check start and end bytes
if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A"))
{
return null;
}
for (int index = 4; index < data.Length - 4; index += 2)
{
bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));
}
//crc test
byte[] packet = bytes.Take(bytes.Count - 2).ToArray();
byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();
uint CalculatedCRC = crc_bytes(packet);
return packet;
}
static public UInt16 crc_bytes(byte[] data)
{
ushort crc = 0xFFFF;
for (int i = 0; i < data.Length; i++)
{
crc ^= (ushort)(Reflect(data[i], 8) << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) > 0)
crc = (ushort)((crc << 1) ^ 0x1021);
else
crc <<= 1;
}
}
crc = Reflect(crc, 16);
crc = (ushort)~crc;
return crc;
}
static public ushort Reflect(ushort data, int size)
{
ushort output = 0;
for (int i = 0; i < size; i++)
{
int lsb = data & 0x01;
output = (ushort)((output << 1) | lsb);
data >>= 1;
}
return output;
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
Write_log(bytesRead.ToString());
if (bytesRead > 0)
{
if (state.buffer[3] == 1)
{
string input = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");
Console.WriteLine("Recived {0} bytes to client.", input);
//byte[] bytes = Unpack(input);
//byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();
//byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };
//serialNumber.CopyTo(response, 4);
//UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());
//response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);
//response[response.Length - 1] = (byte)((sendCRC) & 0xFF);
//Send(handler, response);
// handler.Send(response);
}
else
{
// There might be more data, so store the data received so far.
//state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
// content = state.sb.ToString();
Console.WriteLine("Recived {0} bytes to client.", Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// SaveData(content);
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
// }
}
}
}
private static void Write_log(string logx)
{
StringBuilder sb = new StringBuilder();
string rootPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
sb.Append(logx);
// flush every 20 seconds as you do it
File.AppendAllText(rootPath + "//log.txt", sb.ToString());
sb.Clear();
}
}
}

Related

How to receive data from server with client on c#?

I am making a little game. Server on C++ and client based on C#. I have problems with data receiving, I dont properly understand how it works, do I need second socket to receive? Or the first socket connect and usable for receiving at the same time? This is the client
public class Connection
{
static private string ip = "127.0.0.1";
static private int port = 54000;
static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// static Socket acpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public static void connectToServer()
{
socket.Connect(ip, port);
}
public static void sendData(byte[] buffer)
{
socket.Send(buffer);
}
public static byte[] encodeMessage(string message)
{
byte[] bf = Encoding.ASCII.GetBytes(message);
return bf;
}
public static void recvData()
{
byte[] buf = new byte[256];
byte[] copy = new byte[256];
try
{
socket.Receive(buf);
}
catch (Exception e)
{
Console.WriteLine("Error");
}
if (buf != copy)
{
Console.WriteLine(Encoding.ASCII.GetChars(buf).ToString());
buf = copy;
}
}
}
And this is the server:
int main() {
//init sock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsok = WSAStartup(ver, &wsData);
if (wsok != 0) {
cerr << "Error while init\n";
return 0;
}
//create
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET) {
cerr << "Error while creating\n";
return 0;
}
//bind
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY;
bind(listening, (sockaddr*)&hint, sizeof(hint));
//tell winsock that the socket is for listen
listen(listening, SOMAXCONN);
fd_set master;
FD_ZERO(&master);
FD_SET(listening, &master);
while (true) {
fd_set copy = master;
int socketCount = select(0, &copy, nullptr, nullptr, nullptr);
for (int i = 0; i < socketCount; i++) {
SOCKET sock = copy.fd_array[i];
if (sock == listening) {
//accept connection
SOCKET client = accept(listening, nullptr, nullptr);
//add connection to list(&master)
FD_SET(client, &master);
//send welcome msg to connected client
string welcomeMsg = "Your connected!";
send(client, welcomeMsg.c_str(), welcomeMsg.size() + 1, 0);
}
else{
//accept message
char buf[32];
ZeroMemory(buf, 32);
string str;
int cnt = 0;
int bytesIn = recv(sock, buf, 32, 0);
for (int i = 0; i < sizeof(buf); i++) {
if (buf[i] != '0') {
content[cnt] = buf[i];
cnt++;
}
}
if (bytesIn <= 0) {
closesocket(sock);
FD_CLR(sock, &master);
}
else {
for (int i = 0; i < sizeof(buf); i++) {
cout << content[i];
}
for (int i = 0; i < master.fd_count; i++) {
SOCKET outSock = master.fd_array[i];
if (outSock != listening && outSock != sock) {
send(outSock, content, cnt, 0);
cout << "Message Send..." << endl;
}
}
}
}
}
}
And I have timer where i call recvData(). The problem is that After connection it returns "You're Connected!" but after that it just stuck, doesn't work. If i comment the Socket.Receive I have no problem, but i need this receiving. Thanks
You don't have to use a second socket to receive data, but Send and Receive are synchronous functions, so the thread is blocked until the current operation finishes doing its job. For receiving, the socket has to receive at least on byte in order to unblock the application. If no data is available, Receive will wait indefinitely unless you specify a timeout using ReceiveTimeout property.
To avoid the blocking part, use the asynchronous functions BeginReceive and BeginSend. MSDN has a full server - client example using asynchronous sockets.

Array in Winsock Async

I'm trying to create an array for each person who connect to the server.
The connection works , however, when the server receives information , I have no way of knowing who was who sent this information.
How do I know who is the index of the list " clients" who sent the information ?
Look the code:
Basic definitions
public string Ip { get; set; }
public Socket Ansyc { get; set; }
public int Index { get; set; }
public int Id { get; set; }
public UserConnection(Socket t, int i) { Ansyc = t; Id = i; }
Winsock
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ACESERVER
{
// State object for reading client data asynchronously
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
class WinsockAnsyc
{
//clients
public static List<UserConnection> Clients = new List<UserConnection>(100);
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(100);
while (true) {
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Aguardando conexão...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener );
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar) {
// Signal the main thread to continue.
allDone.Set();
// Socket \o/.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
//Adicionamos ele na lista
Clients.Add(new UserConnection(handler, Clients.Count()));
//Vamos analisar qual index está disponível para o jogador
for (int i = 0; i < 100; i++)
{
if (UserConnection.CheckIndex(i))
{
WinsockAnsyc.Clients[(Clients.Count() - 1)].Index = i;
break;
}
}
//Zerar o Player_HighIndex pra evitar problemas
Globals.Player_HighIndex = 0;
//Vamos atualizar o Player_HighIndex sem frescura
for (int i = 0; i < Clients.Count(); i++)
{
if (WinsockAnsyc.Clients[i].Index > Globals.Player_HighIndex)
{
Globals.Player_HighIndex = WinsockAnsyc.Clients[i].Index;
}
}
//Vamos atualizar o Player_HighIndex para todos os jogadores
SendData.Send_UpdatePlayerHighIndex();
//WinsockAnsyc.Clients[Clients.Count() - 1].ListIndex = Clients.Count() - 1;
Listen.Log(String.Format("Cliente conectado: {0}", Clients.Count() - 1));
// Create the state object.
StateObject state = new StateObject();
state.workSocket = Clients[Clients.Count - 1].Ansyc;
Clients[Clients.Count - 1].Ansyc.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar) {
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
handler.
// Clients[Clients.Count - 1].Ansyc.EndReceive(ar)
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.UTF8.GetString(
state.buffer,0,bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
Server.Network.ReceiveData.SelectPacket(client.Index, content);
if (content.IndexOf("<EOF>") > -1) {
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content );
// Echo the data back to the client.
Send(handler, content);
} else {
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}
Anyone haves tips or a solution?
Your StateObject class should contain all the necessary context you need to identify the client. You should not generally even need to consult the list of clients to handle a single client's individual I/O operation, since that StateObject should be enough.
Without a more complete code example, I can't be more specific than that.

create c# asynchronous socket client in multithreaded environment

I am trying to create asynchronous socket client in multithreaded environment but it is not working correctly.
As below sample code,
If i create new AsyncSocketClient and call StartClent from multi-threaded environment it will process only one or two for rest, it is not processing.(I am creating new AsyncSocketClient with every new request)
Is it because of static variables,
class AsyncSocketClient
{
private static AutoResetEvent sendDone =
new AutoResetEvent(false);
private static AutoResetEvent receiveDone =
new AutoResetEvent(false);
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
static private String response = "";
public void StartClent()
{
Socket workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// clientSock.ReceiveTimeout = 1;
try
{
workSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 8080), new AsyncCallback(ConnectCallBack), workSocket);
connectDone.WaitOne();
Send(s.workSocket, "<EOF>");
sendDone.WaitOne();
Receive(workSocket);
receiveDone.WaitOne();
}
catch(Exception ex)
{
}
}
private void ConnectCallBack(IAsyncResult ar)
{
Socket workSocket = (Socket)ar.AsyncState;
workSocket.EndConnect(ar);
connectDone.Set();
}
private void Receive(Socket client)
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
}
private void ReceiveCallBack(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int byteReceived= client.EndReceive(ar);
if (byteReceived > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.buffer.Length));
Array.Clear(state.buffer, 0, state.buffer.Length);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
private void Send(Socket client,string data)
{
byte[] sendBufer = Encoding.ASCII.GetBytes(data);
client.BeginSend(sendBufer, 0, sendBufer.Length, 0, new AsyncCallback(BeginSendCallBack), client);
}
private void BeginSendCallBack(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
int byteSent= client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", byteSent);
sendDone.Set();
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 30;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
Here is an example of a non blocking client and server with a simple echo implemented. There is no error checking and nothing is closed correctly which should be done. The server has some synchronous code just to make it easier to follow.
Client
public class AsyncClient
{
private const int Port = 9999;
private readonly string _clientId;
private readonly Random _random;
public AsyncClient(int clientId)
{
_clientId = string.Format("Client Id: {0}", clientId);
_random = new Random(clientId);
}
public void StartClient()
{
try
{
var workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var state = new ClientState { WorkSocket = workSocket };
workSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, Port), ConnectCallBack, state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void ConnectCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
state.WorkSocket.EndConnect(ar);
Send(state);
}
private void Receive(ClientState clientState)
{
clientState.WorkSocket.BeginReceive(clientState.Buffer, 0, ClientState.BufferSize, 0, ReceiveCallBack, clientState);
}
private void ReceiveCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
Socket client = state.WorkSocket;
int byteReceived= client.EndReceive(ar);
if (byteReceived > 0)
{
var receivedString = Encoding.UTF8.GetString(state.Buffer, 0, byteReceived);
Console.WriteLine("From Server: " + receivedString);
Array.Clear(state.Buffer, 0, state.Buffer.Length);
state.Count++;
Thread.Sleep(1000 + _random.Next(2000));
Send(state);
}
}
private void Send(ClientState clientState)
{
Console.WriteLine("Sending " + _clientId);
byte[] buffer = Encoding.UTF8.GetBytes(string.Format("Send from Thread {0} Client id {1} Count {2}", Thread.CurrentThread.ManagedThreadId, _clientId,clientState.Count));
clientState.WorkSocket.BeginSend(buffer, 0, buffer.Length, 0, BeginSendCallBack, clientState);
}
private void BeginSendCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
int byteSent= state.WorkSocket.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", byteSent);
Receive(state);
}
}
public class ClientState
{
// Client socket.
public Socket WorkSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] Buffer = new byte[BufferSize];
public int Count = 0;
}
Server
public class AsyncServer
{
private const int Port = 9999;
public void StartServer()
{
var thread = new Thread(Run) {IsBackground = true};
thread.Start();
}
private void Run()
{
Console.WriteLine("Running");
var tcpListener = new TcpListener(IPAddress.Loopback, Port);
tcpListener.Start();
while (true)
{
Console.WriteLine("Before Accept");
var state = new ServerState {WorkSocket = tcpListener.AcceptSocket()};
Console.WriteLine("Before Recieve");
Receive(state);
}
}
private void Receive(ServerState state)
{
state.WorkSocket.BeginReceive(state.Buffer, 0, ServerState.BufferSize, 0, ReceiveCallBack, state);
}
private void ReceiveCallBack(IAsyncResult ar)
{
Console.WriteLine("ReceiveCallBack");
var state = (ServerState) ar.AsyncState;
try
{
int byteReceived= state.WorkSocket.EndReceive(ar);
if (byteReceived > 0)
{
var receivedString = Encoding.UTF8.GetString(state.Buffer, 0, byteReceived);
Console.WriteLine("Received: " + receivedString);
var bytesToSend = Encoding.UTF8.GetBytes("Server Got --> " + receivedString);
Array.Copy(bytesToSend, state.Buffer, bytesToSend.Length);
state.WorkSocket.Send(state.Buffer, 0, bytesToSend.Length, SocketFlags.None);
Array.Clear(state.Buffer, 0, state.Buffer.Length);
Receive(state);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private class ServerState
{
public const int BufferSize = 1024;
public readonly byte[] Buffer = new byte[1024];
public Socket WorkSocket;
}
I have run this using a console you can either have two applications or just launch the client and server separately.
static void Main(string[] args)
{
if (args.Length != 0)
{
var server = new AsyncServer();
server.StartServer();
}
else
{
for(int i = 0; i < 10; i++)
{
var client = new AsyncClient(i);
client.StartClient();
}
}
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}

Infrared command with pocket pc

i have an infrared remote control and i want replace this with my PPC.
My Mitac P550 has an infrared serial port but i dont know how to retrieve and resend the sequence of byte.....
It's possible get the data with SerialPort component of .net for this pourpose?
Thanks
You need to write two (2) methods and install them on each end of your communications: A Send and a Receive.
A generic Send routine would send a message to some host listening on a given port number. Here is a simple example:
public static void Send(string message, string host, int port) {
if (!String.IsNullOrEmpty(message)) {
if (port < 80) {
port = DEF_PORT;
}
Byte[] data = Encoding.ASCII.GetBytes(message);
using (var client = new TcpClient(host, port)) {
var stream = client.GetStream();
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
}
}
A generic Receive routine would need to know the port number to listen on and should return the data that it receives. Here is a simple example of it:
public static string Receive(int port) {
string data = null;
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
using (var client = listener.AcceptTcpClient()) { // waits until data is avaiable
int MAX = client.ReceiveBufferSize;
var stream = client.GetStream();
Byte[] buffer = new Byte[MAX];
int len = stream.Read(buffer, 0, MAX);
if (0 < len) {
data = Encoding.UTF8.GetString(buffer, 0, len);
}
stream.Close();
client.Close();
}
return data;
}
Here is the full class code that I used for this:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace AcpMobile5 {
class TestClass1 : Form {
public const int DEF_PORT = 8000;
private static TcpListener listener;
public static string Receive(int port) {
string data = null;
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
using (var client = listener.AcceptTcpClient()) { // waits until data is avaiable
int MAX = client.ReceiveBufferSize;
var stream = client.GetStream();
Byte[] buffer = new Byte[MAX];
int len = stream.Read(buffer, 0, MAX);
if (0 < len) {
data = Encoding.UTF8.GetString(buffer, 0, len);
}
stream.Close();
client.Close();
}
return data;
}
public static void Send(string message, string host, int port) {
if (!String.IsNullOrEmpty(message)) {
if (port < 80) {
port = DEF_PORT;
}
Byte[] data = Encoding.ASCII.GetBytes(message);
using (var client = new TcpClient(host, port)) {
var stream = client.GetStream();
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
}
}
}
}

How to receive file from multiple client at a time over TCP connection using C#?

I am having a server and multiple clients in my project. Server need to send the files by request, and it store the files from clients. I have coding, that connects with multiple clients but receives one file at time. Other file store requests will proceed after the previous file received completely.
My files size is around 200 MB. So it takes more time to respond all clients. How i will solve this. Any one help me. Thanks in advance.
public partial class Form1 : Form
{
byte[] Echo;
byte[] a;
Thread t1;
int flag = 0;
string receivedPath = "yok";
public delegate void MyDelegate();
private string fileName;
public Form1()
{
t1 = new Thread(new ThreadStart(StartListening));
t1.Start();
InitializeComponent();
}
delegate void SetTextCallback(string text);
public class StateObject
{
// Client socket.
public Socket workSocket = null;
public const int BufferSize = 8069;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
}
public static ManualResetEvent allDone = new ManualResetEvent(true);
public void StartListening()
{
StateObject state = new StateObject();
byte[] bytes = new Byte[8069];
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(ipEnd);
listener.Listen(100);
while (true)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne();
}
}
catch (Exception ex)
{
SetText(ex.ToString());
}
}
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadCallback), state);
flag = 0;
}
public void ReadCallback(IAsyncResult ar)
{
int fileNameLen = 1;
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
try
{
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
if (flag == 0)
{
fileNameLen = BitConverter.ToInt32(state.buffer, 0);
fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
receivedPath = #"D:\" + fileName;
flag++;
}
if (flag >= 1)
{
BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
if (flag == 1)
{
writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
flag++;
}
else
writer.Write(state.buffer, 0, bytesRead);
writer.Close();
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadCallback), state);
}
}
else
{
allDone.Set();
Invoke(new MyDelegate(LabelWriter));
}
}
catch
{
}
}
public void LabelWriter()
{
label1.Text = "Data has been received " + fileName;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
t1.Abort();
}
}
You can trigger your allDone event within the AcceptCallback method. Immidiatly after accepting a client, you can spin of a process that is communicating with that client while in the meantime start listening for the next client.

Categories

Resources