Serial port continuous data reading - c#

I've made and application using WPF and I have to implement serial communication.
Bellow i have the DataReceived function.
The main problem is that the function triggers only sometimes, does anybody have a better solution to DataReceived trigger in WPF?
Below is the connection Connection to ComPort
public static void connnect(string recPort)
{
System.Windows.Threading.DispatcherTimer MyTimer = null;
bool error = false;
String serialpname = recPort;
ComPort = new SerialPort();
if (ComPort.IsOpen == false)
{
ComPort.PortName = serialpname;
ComPort.BaudRate = 38400;
ComPort.Parity = Parity.None;
ComPort.DataBits = 8;
ComPort.StopBits = StopBits.One;
ComPort.DataReceived += new SerialDataReceivedEventHandler(OnSerialDataReceived);
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
try
{
if (ComPort.IsOpen == false)
{
//Open Port
ComPort.Open();
dispatcherTimer.Start();
}
}
catch (System.IO.IOException) { error = true; }
}
}
Below is the timer that interogates the port
private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
ComPort.Write(eot + "11" + STX + "2170" + ENQ); // get pos
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The datareceived event
public static void OnSerialDataReceived(object sender,
SerialDataReceivedEventArgs args)
{
bool isString = true;
try
{
Thread.Sleep(100);// this solves the problem
byte[] readBuffer = new byte[ComPort.ReadBufferSize];
int readLen = ComPort.Read(readBuffer, 0, readBuffer.Length);
string readStr = string.Empty;
if (isString)
{
readStr = Encoding.Default.GetString(readBuffer, 0, readLen);
if(readStr.Length > 10)
{
if (readStr.StartsWith("\u0002"))
{
Position = (Mid(readStr, 2, 5));
Messenger.Default.Send("NewPos");
}
else
{
Position = (Mid(readStr, 31, 4));
Messenger.Default.Send("NewPos");
}
}
}
else
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < readLen; i++)
{
stringBuilder.Append(readBuffer[i].ToString("X2") + " ");
}
readStr = stringBuilder.ToString();
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
Console.WriteLine(ex);
}
}

Problem solved, i have added a Thread.Sleep(100); in the datareceived function. The buffer was not filled with the incoming data and seems that was the cause.
Thank you.

Related

How to transfer the data from Chrome Browser Console onto C# file

We are getting joint data in JSON Objects format. The data is streaming live on the Chrome Console as you can see in the picture.
How do we take this data (from the Chrome Console) and send it over to a C# file on the computer in real-time?
From Console: JSON Object data from kinectv2
Here is some basic c# websocket code, it doesnt have to convert the data it receives to a string. I was just testing some stuff
C# simple websocket connection
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
public partial class MainWindow : Window
{
private Websocket_listen _listener;
public MainWindow()
{
_listener = new Websocket_listen("127.0.0.1", 13000);
_listener.StringReceived += _listener_StringReceived;
_listener.Start();
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_running = false;
_listener.Stop();
}
private void _listener_StringReceived(string received)
{
}
}
public class Websocket_listen
{
public readonly int port = 13000;
public readonly IPAddress localAddr;
private TcpListener server = null;
private TcpClient client = null;
private NetworkStream stream = null;
private bool connected = false;
private byte[] bytes = new byte[2048];
private byte[] _last_key = new byte[4];
private int _last_message_length;
private bool read_more_message;
private Thread _current_thread;
private bool _running = true;
private int _received = 0;
private StringBuilder _results = new StringBuilder();
public event Action<string> StringReceived = null;
public Websocket_listen(string ipaddress, int port)
{
this.port = port;
localAddr = IPAddress.Parse(ipaddress);
server = new TcpListener(localAddr, port);
}
public void _running_loop()
{
while (_running)
{
try
{
server.Server.ReceiveTimeout = 5000;
server.Server.SendTimeout = 5000;
client = server.AcceptTcpClient();
// Get a stream object for reading and writing
stream = client.GetStream();
}
catch (Exception ex)
{
continue;
}
while (_running)
{
try
{
try
{
l.AcquireWriterLock(-1);
if (messsages.Count > 0)
{
byte[] msg = System.Text.Encoding.ASCII.GetBytes(messsages[0]);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes("Connected to " + Environment.MachineName);
Array.Copy(msg, 0, bytes, 2, msg.Length);
bytes[0] = 0x81;
bytes[1] = (byte)msg.Length;
// Send back a response.
stream.Write(bytes, 0, msg.Length + 2);
messsages.RemoveAt(0);
}
}
finally
{
l.ReleaseWriterLock();
}
}
catch { }
try
{
_received = stream.Read(bytes, 0, bytes.Length);
}
catch
{
continue;
}
if (_received == 0)
continue;
if (!connected)
{
_is_connection();
continue;
}
if (!_parse_message())
break;
}
}
try
{
stream.Close();
client.Close();
}
catch (Exception ex)
{
}
}
private bool _parse_message()
{
int offset = 0;
int message_length = 0;
if (read_more_message)
{
_last_message_length -= bytes.Length;
message_length = _last_message_length;
if (message_length < bytes.Length)
message_length += 8;
}
else
{
_results.Clear();
var trigger = bytes[0];
var magic_byte = bytes[1];
bool is_text = (0x1 & trigger) != 0;
bool is_fin = (0x80 & trigger) != 0;
if (trigger == 0x88)
{
connected = false;
return false;
}
/*
text = 0x81
binary = 0x82
close 0x88
ping 0x89
pong -0x8A
*/
if (!is_fin)
{
return true;
}
if (!is_text)
{
return true;
}
//If the second byte minus 128 is between 0 and 125, this is the length of message.
//If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer) are the length.
var r = magic_byte - 128;
var key_starts_at = 0;
if (r <= 125)
{
key_starts_at = 2;
message_length = r;
}
else if (r == 126)
{
key_starts_at = 4;
message_length = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
}
else if (r == 127)
{
key_starts_at = 10;
for (var m = 7; m >= 0; --m)
{
message_length += bytes[m] << (8 * (7 - m));
}
}
else
{
// not documented
}
//// because its encoded
_last_message_length = message_length;
Array.Copy(bytes, key_starts_at, _last_key, 0, 4);
offset = key_starts_at + 4;
}
for (var mx = 0; mx < message_length && offset + mx < bytes.Length; ++mx)
{
bytes[offset + mx] = (byte)(bytes[offset + mx] ^ _last_key[mx % 4]);
}
var new_result = System.Text.Encoding.ASCII.GetString(bytes, offset, Math.Min(message_length, bytes.Length - offset));
_results.Append(new_result);
read_more_message = message_length > bytes.Length;
if (!read_more_message)
{
try
{
StringReceived?.Invoke(_results.ToString());
}
catch (Exception ex)
{
}
}
return true;
}
private void _is_connection()
{
try
{
string data = System.Text.Encoding.ASCII.GetString(bytes, 0, _received);
if (!new Regex("^GET").IsMatch(data))
return;
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
connected = true;
}
catch (Exception ex)
{
}
}
public void Stop()
{
_running = false;
}
public void Start()
{
// Start listening for client requests.
server.Start();
_current_thread = new Thread(new ThreadStart(_running_loop));
_current_thread.Start();
}
ReaderWriterLock l = new ReaderWriterLock();
List<string> messsages = new List<string>();
internal void Send(string msg)
{
try
{
l.AcquireWriterLock(-1);
messsages.Add(msg);
}
catch
{
}
finally
{
l.ReleaseWriterLock();
}
}
}
not a very robust javascript simple websocket to connect to c# with the same port
try {
var isopen = false;
connection = new WebSocket('ws://127.0.0.1:13000');
// When the connection is open, send some data to the server
connection.onopen = function () {
isopen = true;
connection.send('Ping'); // Send the message 'Ping' to the server
$('#open_messages').html("connection made\r\n<br>");
$('#socket_errors').html("");
};
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ', error);
$('#socket_errors').html(error.currentTarget.url + " failed\r\n<br><button id=\"reconnect\">Try to connect</button>");
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ', e);
$('#messages').append(e.data + "\r\n<br>");
};
connection.onclose = function(x) {
console.log('closed ', x);
$('#open_messages').html("Disconnected\r\n<br>");
$('#socket_errors').html("<button id=\"reconnect\">Connect</button>");
};
} catch (err) {
console.log(err);
}
That should get you started sending data back and forth, but will probably need extra exception handling.
Not sure if sending strings across is efficient, by you could probably change the data later.

Serial port keep prompt time out error

private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (Clos_flag) return;
try
{
Listening = true;
if (serialPort.IsOpen)
{
this.txt_weight.Invoke(new MethodInvoker(delegate
{
serialPort.NewLine = "\r";
string weight = serialPort.ReadLine();
weight = weight.Trim();
MessageBox.Show(weight);
if (weight.IndexOf("i") > 0)
{
weight = weight.Substring(3, 8);
txt_weight.Text = weight.Substring(0, weight.LastIndexOf("0") + 1);
}
}));
}
}
catch (Exception eg)
{
MessageBox.Show(eg.ToString());
}
finally
{
Listening = false;
}
}
I use the above code to read the weighing machine, but it keep on prompt the timeout error I'm not sure which part of the coding is wrong.
You check your configure serialport.
It may be error while run code serialPort.Open().
you can refer code:
void InitialComport1()
{
mySerialPort1 = new SerialPort(Temp._comport1);
if (mySerialPort1.IsOpen)
{
mySerialPort1.Close();
}
mySerialPort1.BaudRate = Temp._baudRate1;
mySerialPort1.Parity = Parity.None;
mySerialPort1.StopBits = StopBits.One;
mySerialPort1.DataBits = Temp._dataBit1;
mySerialPort1.Handshake = Handshake.None;
mySerialPort1.RtsEnable = true;
mySerialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler1);
try
{
mySerialPort1.Open();
}
catch
{
Messagebox.Show("Error myserialPort1")
}
}
private void DataReceivedHandler1(object sender, SerialDataReceivedEventArgs e)
{
try
{
string indata = mySerialPort1.ReadLine();
try
{
string mass = indata.Substring(7, 7);
SetText1((Convert.ToInt32(mass)).ToString());
}
catch
{
string mass = indata.Substring(3, 7);
SetText1((Convert.ToInt32(mass)).ToString());
}
}
catch (Exception eg)
{
MessageBox.Show(eg.ToString());
}
}

Cancel "tcplistener" from backgroundworker's CancelAsync()

I have a Windows form from which when a button is clicked an instance of Backgroundworker starts a tcplistener method in another class.
I would like to be able to cancel the tcplistener after it's started or while it's receiving\writing data to disk.
I have set the backgroundworker arguments to be available for the tcplistener class so that the cancellationpendingargument can be used to cancel operations in the tcplistener class.
The issue is that once the "tcplistener.server" is started, if the cancel button is clicked, the listener is not being stopped or terminated.
To achieve this I have put the tcplistener code in a while (bgw.CancellationPending != true) assuming if the argument is wrong the listening would be cancelled
Here is my back groundworker code:
private void startBtn_Click(object sender, EventArgs e)
//private void startBtn_Click(BackgroundWorker bw, EventArgs e)
{
if (bgw.IsBusy != true)
{
if (ipTxt.Text != "" && portTxt.Text != "" && dirTxt.Text != "" && bufferTxt.Text != "")
{
cancelBtn.Enabled = true;
listenerLabel.Text = "...";
resultLabel.Text = "...";
netwrkLst.Enabled = false;
ipTxt.Enabled = false;
portTxt.Enabled = false;
bufferTxt.Enabled = false;
dirTxt.Enabled = false;
brwsBtn.Enabled = false;
startBtn.Enabled = false;
this.bgw.RunWorkerAsync();
}
else
{
MessageBox.Show("Fill in all fields first");
}
}
}
//This event handler cancels the backgroundworker
private void cancelBtn_Click_1(object sender, EventArgs e)
{
//if (bgw.WorkerSupportsCancellation == true)
if (bgw.IsBusy == true)
{
// Cancel the asynchronous operation.
this.bgw.CancelAsync();
cancelBtn.Enabled = false;
startBtn.Enabled = true;
listenerLabel.Text = "Listening canceled.";
resultLabel.Text = "...";
netwrkLst.Enabled = true;
ipTxt.Enabled = true;
portTxt.Enabled = true;
bufferTxt.Enabled = true;
dirTxt.Enabled = true;
brwsBtn.Enabled = true;
}
}
// This event handler is where the work is done.
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
if (this.bgw.CancellationPending == true)
{
e.Cancel = true;
return;
}
listener.tcp(
ipTxt.Text,
portTxt.Text,
dirTxt.Text,
bufferTxt.Text, bgw, e);
}
// This event handler updates the progress.
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
// This event handler deals with the results of the background operation.
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
resultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
resultLabel.Text = "Error: " + e.Error.Message;
}
else
{
resultLabel.Text = "Done!";
}
}
And here is my tcplistener code:
namespace McServer
{
public class listener
{
// Raise the UpdateLabel event, passing "Outside" as
// the message.
public static event Action<string> UpdateLabel;
public static event Action<string> UpdateLabel2;
//public volatile bool shutdown = false;
public static void tcp(string ip, string portID, string path, string buffer, BackgroundWorker bgw, DoWorkEventArgs ev)
{
//if (bgw.CancellationPending == true)
//{
// ev.Cancel = true;
// return;
//}
//while (bgw.CancellationPending != true)
//{
TcpListener server = null;
string time = DateTime.Now.ToString("yyyyMMdd" + "_" + "HH-mm-ss");
while (bgw.CancellationPending != true) try
{
// Set the TcpListener.
Int32 port = Int32.Parse(portID);
IPAddress localAddr = IPAddress.Parse(ip);
Int32 buff = Int32.Parse(buffer);
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
// Buffer for reading data
//Byte[] bytes = new Byte[1000 * 1024];
Byte[] bytes = new Byte[buff];
server.Start();
// Enter the listening loop.
while (true)
{
UpdateLabel("Waiting for a connection...");
// Perform a blocking call to accept requests.
// Can also also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
UpdateLabel("Connected...");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
int j = 0;
int k = 0;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) > 0)
{
j++;
k = k + i;
if (k >= 1024)
{
k = k / 1024;
UpdateLabel("Received:" + k + " MB");
}
if (k >= 1024 * 1000)
{
k = k / 1024 / 1024;
UpdateLabel("Received:" + k + " GB");
}
UpdateLabel("Received:" + k + " Bytes");
//write to file
using (FileStream stream2 = new FileStream(path + j + "_" + time + "_" + ".tcp", FileMode.Create))
{
stream2.Write(bytes, 0, i);
stream2.Close();
}
// Send back a response.
stream.Write(bytes, 0, bytes.Length);
}
// Shutdown and end connection
client.Close();
UpdateLabel2("Connection closed by client...");
}
}
catch (SocketException e)
{
UpdateLabel2("An error occured: SocketException:" + e);
}
finally
{
// Stop listening for new clients.
server.Stop();
UpdateLabel2("Listening stopped...");
}
//}
{
ev.Cancel = true;
return;
}
}
}
}

Memory leak C# Async (got stack)

I have a application where I switched out the communication from TCPClient to using SocketAsyncEventArgs, but I do have a problem that occures when the application been running for a few hours, and I cant seem to find it. Here is my Stack Trace, anyone got an idea?:
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.OutOfMemoryException
Stack:
at System.Threading.ThreadPoolWorkQueue.Enqueue(System.Threading.IThreadPoolWorkItem, Boolean)
at System.Threading.ThreadPool.QueueUserWorkItemHelper(System.Threading.WaitCallback, System.Object, System.Threading.StackCrawlMark ByRef, Boolean)
at System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, System.Object)
at System.IO.Ports.SerialStream+EventLoopRunner.CallEvents(Int32)
at System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
Code:
public Client(Form1 parent)
{
todo = new ArrayList();
buffert = new List<MsgStruct>();
this.parent = parent;
this.ip = ini.GetFromIni("CONFIG", "IP");
this.port = ini.GetFromIni("CONFIG", "PORT");
data = new byte[100000];
// Addres of the host.
IPAddress[] addressList = host.AddressList;
// Instantiates the endpoint and socket.
this.hostEndPoint = new IPEndPoint(addressList[addressList.Length - 1], Convert.ToInt32(port));
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
startTimer = new System.Timers.Timer();
startTimer.Elapsed += new ElapsedEventHandler(startSendLoop);
startTimer.Interval = 1000;
startTimer.Start();
sendTimer = new System.Timers.Timer();
sendTimer.Elapsed += new ElapsedEventHandler(sendloop);
sendTimer.Interval = 500;
sendTimer.Start();
pingTimer = new System.Timers.Timer();
pingTimer.Elapsed += new ElapsedEventHandler(pingTimer_Elapsed);
pingTimer.Interval = 13000;
pingTimer.Start();
}
internal void Disconnect()
{
try
{
clientSocket.Disconnect(true);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
MessageBox.Show(e.ToString());
}
}
public void Dispose()
{
try
{
autoConnectEvent.Close();
autoSendReceiveEvents[SendOperation].Close();
autoSendReceiveEvents[ReceiveOperation].Close();
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
catch (Exception ex)
{
}
}
public void pingTimer_Elapsed(object sender, ElapsedEventArgs e)
{
sendPing = true;
}
public void startSendLoop(object sender, ElapsedEventArgs e)
{
try
{
if (!this.clientSocket.Connected)
{
connectArgs = new SocketAsyncEventArgs();
connectArgs.UserToken = this.clientSocket;
connectArgs.RemoteEndPoint = this.hostEndPoint;
connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
clientSocket.ConnectAsync(connectArgs);
bool test = autoConnectEvent.WaitOne(5000);
gotData = true;
lastTime = DateTime.Now;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
private void ProcessError(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
if (s.Connected)
{
// close the socket associated with the client
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
// throws if client process has already closed
}
finally
{
if (s.Connected)
{
s.Close();
}
}
}
}
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
try
{
autoConnectEvent.Set();
// Set the flag for socket connected.
this.connected = (e.SocketError == SocketError.Success);
}
catch (Exception ex)
{
}
}
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
try
{
while (true)
{
if (canReceive)
{
canReceive = false;
string stringData;
int recv = 0;
for (int i = 0; i < e.Buffer.Length; i++)
{
if (e.Buffer[i] != 0)
recv++;
else
break;
}
if (recv > 0)
{
int count = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] != 0)
count++;
else
break;
}
e.Buffer.CopyTo(data, count);
lastTime = DateTime.Now;
gotData = true;
if ((byte)data[count + recv - 1] == (byte)255)
{
int cnt = -1;
for (int i = 0; i < count + recv; i++)
{
if (data[i] == (byte)254)
{
cnt = i;
break;
}
}
int nr = (count + recv) - cnt - 2;
byte[] tmp = new byte[nr];
for (int i = 0; i < nr; i++)
{
tmp[i] = data[cnt + i + 1];
}
string crc = Encoding.UTF8.GetString(tmp);
stringData = Encoding.UTF8.GetString(data, 0, cnt);
MsgStruct msgs = new MsgStruct(stringData);
msgs.setCrc(crc);
todo.Add(msgs);
data = new byte[100000];
}
}
canReceive = true;
break;
}
else
Thread.Sleep(10);
}
handleToDo();
autoSendReceiveEvents[SendOperation].Set();
e.Dispose();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
private void OnSend(object sender, SocketAsyncEventArgs e)
{
try
{
// Signals the end of send.
sendSuccess = true;
autoSendReceiveEvents[ReceiveOperation].Set();
if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Send)
{
// Prepare receiving.
Socket s = e.UserToken as Socket;
byte[] receiveBuffer = new byte[100000];
e.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
s.ReceiveAsync(e);
}
}
else
{
this.ProcessError(e);
}
}
catch (Exception ex)
{
}
}
public void sendloop(object sender, ElapsedEventArgs e)
{
try
{
sendTimer.Enabled = false;
if (this.clientSocket.Connected)
{
byte[] data = new byte[1024];
bool extendedTime = false;
DateTime tmpDate = lastTime.AddSeconds(30);
if (DateTime.Now > tmpDate)
{
gotData = false;
}
if (canUseBuffert && sendSuccess)
{
canUseBuffert = false;
if (buffert.Count > 0)
{
if (buffert[0] != null && buffert[0].getMsg().Length != 0)
{
byte[] ba = Encoding.UTF8.GetBytes(buffert[0].getMsg());
if (buffert[0].getCrc() == "")
{
ulong tmp = CRC.calc_crc(ba, ba.Length);
buffert[0].setCrc(tmp.ToString("X"));
}
if (buffert[0].canSendByTimeout())
{
string crcStr = "?" + buffert[0].getCrc() + "?";
byte[] bb = Encoding.UTF8.GetBytes(crcStr);
crcStr = Encoding.UTF8.GetString(bb);
byte[] fullMsg = new byte[ba.Length + bb.Length];
bb[0] = 254;
bb[bb.Length - 1] = 255;
ba.CopyTo(fullMsg, 0);
bb.CopyTo(fullMsg, ba.Length);
string s = System.Text.UTF8Encoding.ASCII.GetString(fullMsg);
this.clientSocket.NoDelay = false;
completeArgs = new SocketAsyncEventArgs();
completeArgs.SetBuffer(fullMsg, 0, fullMsg.Length);
completeArgs.UserToken = this.clientSocket;
completeArgs.RemoteEndPoint = this.hostEndPoint;
completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
sendSuccess = false;
// Start sending asyncronally.
clientSocket.SendAsync(completeArgs);
}
}
}
else
{
extendedTime = true;
byte[] bba = Encoding.UTF8.GetBytes("X");
this.clientSocket.NoDelay = true;
completeArgs = new SocketAsyncEventArgs();
completeArgs.SetBuffer(bba, 0, bba.Length);
completeArgs.UserToken = this.clientSocket;
completeArgs.RemoteEndPoint = this.hostEndPoint;
completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
sendSuccess = false;
// Start sending asyncronally.
clientSocket.SendAsync(completeArgs);
}
}
canUseBuffert = true;
if (!clientSocket.Connected && !gotData)
Disconnect();
}
sendTimer.Enabled = true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
sendTimer.Enabled = true;
}
}
I would have a serious look at the data = new byte[100000]; calls in your communication routines. Because it is larger than 85KB (85,000 bytes to be exact) memory blocks you're filling up (and fragmenting) your LOH. This can cause OutOfMemoryException issues. See this link

From C# to Android via Socket. Can't find my mistake

The problem - I can't get this functions working. I see in LogCat that socket is connected to c# server, but I don't see received data. What I'm doing wrong?
Here is c# function with MessageBoxes for checking:
private void receiveConnection(){
Socket myHandler = null;
bool isConnected = false;
while (true)
{
if (!isConnected)
{
myHandler = wSocket.Accept();
isConnected = true;
MessageBox.Show("We have client!");
}
if (sendDataToAndroid)
{
try
{
sendDataToAndroid = false;
NetworkStream stream = new NetworkStream(myHandler);
StreamWriter sw = new StreamWriter(stream);
string myMsg = "";
myMsg += temp_F.Length + " ";
temp_F[0] = 3.151F;
temp_F[1] = 1.415F;
temp_F[2] = 5.572F;
temp_F[3] = 6.320F;
for (int i = 0; i < temp_F.Length; i++)
{
myMsg += temp_F[i] + " ";
}
byte[] msg = Encoding.ASCII.GetBytes(myMsg);
MessageBox.Show("Data to send: " + myMsg);
try
{
myHandler.Send(msg);
MessageBox.Show("Data has been sent!");
}
catch (Exception e) {
MessageBox.Show("Error while sending data!");
}
}
catch (Exception e)
{
isConnected = false;
myHandler.Close();
myHandler = null;
MessageBox.Show("Error while sending data...");
}
}
}
}
And here is Android function which is always trying to receive data:
public class SendThread implements Runnable {
public void run()
{
Socket socket = null;
BufferedReader in = null;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
}
}
// Get from the server
try {
Log.d("Connection: ", "connected");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = line.split(" ");
int currTempSize = Integer.parseInt(tokens[0]);
currentTemp = new double[currTempSize];
for (int i = 0; i < currTempSize; i++)
currentTemp[i] = (Double) nf.parse(tokens[i+1]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currTempSize; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
}
}
catch (Exception e) {
socket = null;
in = null;
Log.d("Connection: ", "lost.");
}
}
}
}
Your Java code reads a line at a time but you never sent a line terminator from C#.
You could append one to myMsg manually, or you could use the sw.WriteLine() method on your StreamWriter (which don't otherwise seem to be using). After calling sw.WriteLine() you will probably have to call sw.Flush().

Categories