I am writing my program in Microsoft Visual Studio 2013 professional C#. I used the debugger and I looked at my array called Message3 and it has the right information, but when it gets to the connected computer modbus program, the message is different. So I used Wireshark and wireshark agrees with the Modbus program. It is weird because it only does it for some values
like the value 7600 in modbus it is sent out in two registers as 29 and 176 and my program has that in the array but wireshark is seeing 29 194 176.
it somehow added a 194 that was not in my array.
[0] 0 '\0' char
[1] 4 '' char
[2] 0 '\0' char
[3] 0 '\0' char
[4] 0 '\0' char
[5] 5 '' char
[6] 1 '' char
[7] 3 '' char
[8] 2 '' char
[9] 29 '' char
[10] 176 '°' char
that is what my debugger has and this is what wire shark see:
0 4 0 0 0 6 1 3 0 5 0 1 03 02 1d c2 b0
I have tried both: writer.Flush and writer.FlushAsync but nothing helps.
again it is only some values it does this too.
here is my code :
void Listener_function()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
listener = null;
try
{
listener = new TcpListener(IPAddress.Parse(Moxa_IPtxt.Text), Convert.ToInt16(modemPorttxt.Text));
listener.Start();
// ErrorBox.Text = " EchoServer started ... /n";
connect_flag = true;
MessageBox.Show(" waiting for incoming client connections.../n /r");
client = listener.AcceptTcpClient();
MessageBox.Show(" Accepted new client coneection ...");
StreamReader reader = new StreamReader(client.GetStream());
StreamWriter writer = new StreamWriter(client.GetStream());
while (true)
{
string s = string.Empty;
char[] temp = new char[12];
int s1 = reader.Read(temp, 0, 12);
int Registers_number = (((int)temp[10] << 8) + (int)temp[11]);
int Message_Size = (Registers_number * 2) + 9;
char[] Message3 = new char[Message_Size];
TCPProcessing(temp, Message3);
if (writeData == true)
{
writer.Write(Message3);
// writer.Flush();
writer.FlushAsync();
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
//button1.Text = "Connect";
//ErrorBox.Text = e.ToString();
}
finally
{
if (listener != null)
{
listener.Stop();
}
}
}
any ideas ?
again I had a breakpoint at the } after FlushAsync and I copy what message has and it does not have a 194 ( Please see above)
Brandon, you don't seem to read carefully what I wrote .
don't use StreamReader/StreamWriter which are for text operations. Use directly client.GetStream
Here is a code to show you
var m = new MemoryStream();
var wr = new StreamWriter(m);
wr.Write(new char[] { (char)29, (char)176 }, 0, 2);
wr.Flush();
var bytes2 = m.ToArray();
content of bytes2 is: 29,194,176 as in your case. So I repeat, use client.GetStream, not StreamReader/StreamWriter
Related
I have a problem with a socket server receiving first 2 bytes from the client correctly and the rest are just null bytes, and the packet length is correct as well,
Client send function:
internal void Send(byte[] _data) {
if (!IsValid()) return;
try {
ushort wrLenBuf = (ushort)_data.Length;
byte[] data = new byte[2 + wrLenBuf];
BinaryPrimitives.WriteUInt16LittleEndian(data, wrLenBuf);
xMemUtils.MemCopy2(_data, 0, ref data, 2);
string s = "";
foreach (var b in _data) s += b + " ";
Console.WriteLine(s);
stream.WriteAsync(data, 0, wrLenBuf + 2);
} catch (Exception e) {
Console.WriteLine(e.ToString());
Close();
}
}
Which produces the output:
2 4 8 48 48 48 48 48 48 48 48 48 48 48 48
which is the correct bytes of 15 length.
The server ReceivePacket function:
int totBytesRead;
private async void RcvPkt(ushort pktSz) {
Console.WriteLine("PktSz: " + pktSz);
totBytesRead = 0;
byte[] buf = new byte[pktSz];
while (totBytesRead < pktSz) {
readLen = await stream.ReadAsync(buf.AsMemory(totBytesRead, pktSz - totBytesRead));
if (readLen == 0) {
Close();
return;
}
totBytesRead += readLen;
Console.WriteLine("TotalBytesRead: " + totBytesRead);
}
string s = "RcvArr: ";
foreach (var b in buf) s += b + " ";
Console.WriteLine(s);
//Console.WriteLine("PSz: " + pktSz + " BfLen: " + buf.Length + " | " + Encoding.UTF8.GetString(buf, 0, pktSz));
//Packet.Handler.thiz.Handle(this, buf);
RcvPktSz();
}
Output:
PktSz: 15
TotalBytesRead: 15
RcvArr: 2 4 0 0 0 0 0 0 0 0 0 0 0 0 0
I tried with this 15byte length array, 41byte length array, both receive full packet but only the first 2 bytes correctly and the rest are null bytes \0.
That's from client to server, on the other hand when sending a string from the server to client it gets it correctly.
I would appreciate anyone helping or having any idea of what's goin wrong here.
I'm porting a legacy application from vb6 to c#, using serial port communication with a MSR206 Magstripe reader/writer. I can reset, connect, flash lights, read and write to the device successfully in both applications, and, verify the data being read/written with the EZWriter software that came with the MSR206.
However, I am having problems reconciling the programmers manual with the data being received over the serial port.
The legacy application treats any response with the byte value / ASCII code 94 ^, as an ACK. However, the user manual doesn't mention this as a valid response code. Also, I thought the ASCII code 6 is an ACK. Either way, if I treat this character as a "Success", everything works.
When I try to perform an operation, such initialisation, I only receive this one character as the response, and not what output the manual says.
e.g.
"8.1 MSR 206 INITIALIZATION
Command code: < ESC > a (Reset)
Command code: < ESC > e (Serial port test)
Response : Command test ACK: < ESC >y
Command code: < ESC > a (Reset)"
When running the initialisation, I'd expect byte[2] {27, 121} (< ESC >, y) as a response. Instead, I get:
Send: byte[2] {27, 97} (< ESC >, a)
Receive: byte[1] {94} (^)
Send: byte[2] {27, 101} (< ESC >, e)
Receive: byte[1] {94} (^)
Send: byte[2] {27, 97} (< ESC >, a)
Receive: byte[1] {94} (^)
If I try to return the firmware version:
Command: Get firmware version
Command code: < ESC > v
Response: < ESC > [version]
Description: This command can get the firmware version of MSR206.
* [version] is a 5 bytes version number, format is “ REV?X.XX “
MSR206? = 0 MSR206HC? = H MSR206HL? = U
I only receive the ^, and a ?.
Send: byte[2] {27, 118} (< ESC >, v)
Receive: byte[2] {94, 161} (^, ?)
Sample code:
using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
public class MSR206Test
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
_serialPort = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);
_serialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
_serialPort.Open();
_continue = true;
Console.WriteLine("Type Command 1 to 6 or QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
switch (message)
{
case "1":
Console.WriteLine("Send ESC > reset");
_serialPort.Write(new byte[] { 27, 97 }, 0, 2);
break;
case "2":
Console.WriteLine("2 Sending ESC > firmware version)");
_serialPort.Write(new byte[] { 27, 118 }, 0, 2);
break;
case "3":
Console.WriteLine("3 Sending ESC > Serial port test)");
_serialPort.Write(new byte[] { 27, 101 }, 0, 2);
break;
case "4":
Console.WriteLine("4 Sending ESC > ram test)");
_serialPort.Write(new byte[] { 27, 87 }, 0, 2);
break;
case "5":
Console.WriteLine("5 Sending ESC > del)");
_serialPort.Write(new byte[] { 27, 127 }, 0, 2);
break;
case "6":
Console.WriteLine("6 ESC > flash)");
_serialPort.Write(new byte[] { 27, 40 }, 0, 2);
break;
}
}
}
_serialPort.Close();
}
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var bytes = _serialPort.BytesToRead;
var buffer = new byte[bytes];
_serialPort.Read(buffer, 0, _serialPort.BytesToRead);
for(var i = 0; i < buffer.Length; i++)
{
Console.WriteLine($"Response index ({i}) : " + buffer[i]);
}
var data = Encoding.ASCII.GetString(buffer);
Console.WriteLine($"Response ({buffer.Length}) : " + data);
}
}
I must be missing something simple, as I can encode and decode cards, I just cannot make sense on what's going on / why the output doesn't match the manual?
It's a device age issue, it doesn't look like the firmware on this model supports these commands. I've used a new magstripe and it functions as per the manual.
I've reached out to the manufacturer for a device manual that matches this revision firmware.
I'm trying to send some data with header from c++ tcp socket to c# tcp socket. Please see my code below for this appraoch.
C++ code to send data
typedef struct tag_TCP_Header_Data{
int iMessageID;
int iDataLen;
int iCheckSum;
}TCP_HEADER_DATA;
TCP_HEADER_DATA stTcpHeader = {0};
char acSendBuf[1024] = {0};
char chData[38] = "01 April - I compile my simple program";
stTcpHeader.iMessageID = 100;
stTcpHeader.iDataLen = 38;
stTcpHeader.iCheckSum = 190;
memcpy(acSendBuf, &stTcpHeader, sizeof(stTcpHeader));
memcpy(acSendBuf+sizeof(stTcpHeader), &chData, sizeof(chData));
int iSent = SendSocketData(acSendBuf, sizeof(acSendBuf));
C# code to receive data
public void AddBytesFromArrayToArrayList(ref ArrayList arrayListReceivedBytes, byte[] byteReceivedBuffer, int intLength)
{
for (int intCount = 0; intCount < intLength; intCount++)
{
arrayListReceivedBytes.Add(byteReceivedBuffer[intCount]);
}
}
public byte[] ReceiveMessage()
{
lock (this.objectToLock)
{
byte[] byteReceivedBuffer = new byte[1024];
int intBytesReceived = 0;
ArrayList arrayListReceivedBytes = new ArrayList();
do
{
try
{
intBytesReceived = this.socket.Receive(byteReceivedBuffer, byteReceivedBuffer.Length, SocketFlags.None);
this.AddBytesFromArrayToArrayList(ref arrayListReceivedBytes, byteReceivedBuffer, intBytesReceived);
Thread.Sleep(100);
}
catch (SocketException ex)
{
string str = ex.Message;
}
catch (Exception ex)
{
string str = ex.Message;
}
}
while (this.socket.Available > 0);
byte[] byteReceived = (byte[])arrayListReceivedBytes.ToArray(typeof(byte));
return byteReceived;
}
}
Server gets the header data with blank in between like this. I know something I'm missing in c# code for this int and char byte data conversion. Can anyone point me out?
[0] 100 byte
[1] 0 byte
[2] 0 byte
[3] 0 byte
[4] 160 byte
[5] 0 byte
[6] 0 byte
[7] 0 byte
[8] 190 byte
[9] 0 byte
[10] 0 byte
[11] 0 byte
[12] Correct data
[..] Correct data
[..] Correct data
How can I send Large data to WebSocket in Java Script?
Using below code I am able to send data for 126 characters but not more then this. (Written in C#)
public static void SendData(string text)
{
foreach (SocketClient client in ClientList)
{
if (client.Client.Connected)
{
try
{
NetworkStream l_Stream = client.Client.GetStream();
List<byte> lb = new List<byte>();
lb = new List<byte>();
lb.Add(0x81);
int size = text.Length;
lb.Add((byte)size);
lb.AddRange(Encoding.UTF8.GetBytes(text));
l_Stream.Write(lb.ToArray(), 0, size + 2);
}
catch
{
CloseClient(client);
}
}
}
}
}
Can someone please help me? I tried to use so many things but none of them are working for me.
I am using Chrome 25 for the same.
This is how a websocket frame looks according to RFC 6455:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
You are setting the payload length of the websocket frame in byte 1 (the 2nd byte - first byte is byte 0). A byte can only have 256 states. But the first bit of byte 1 is used for the masking flag. So you can only represent values from 0 to 127.
When the payload length is larger than 125, you have to set byte 1 to 126 and put the length into byte 2 and 3 ("Extended payload length"). When your payload is even longer than 65535 bytes, you have to set byte 1 to 127 and put the payload length into the bytes 2-9 ("Extended payload length" and "Extended payload length continued"). When your payload length is even larger than 64bit (16 Exabyte, or about 16 million Terabyte), then... you should rather send a bunch of trucks filled with hard drives.
More details about that can be found in the official Websocket RFC.
You can send any size of data to WebSocket but large data will be fragmented.
Check this: https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5 and 5.4
and
pastebin.com/TxGZaHTY
and
http://buildnewgames.com/websockets/
for more info.
Referred from this blog. There could be a limit for single payload size to send and receive in the WebSocket server. For instance, in tomcat, by default it is 8192 bytes, checkout org.apache.tomcat.websocket.textBufferSize in tomcat's doc.
So, make sure if there is any payload size limit in your WebSocket server, if yes then receive it as partial payloads.
package GoodExample;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import sun.misc.BASE64Encoder;
/**
*
* #author
* Anders, Improved by Christopher Price
*/
public class WebRTCSignal {
public static final int MASK_SIZE = 4;
public static final int SINGLE_FRAME_UNMASKED = 0x81;
private ServerSocket serverSocket;
private Socket socket;
public WebRTCSignal() throws IOException {
serverSocket = new ServerSocket(1337);
connect();
}
private void connect() throws IOException {
System.out.println("Listening");
socket = serverSocket.accept();
System.out.println("Got connection");
if(handshake()) {
listenerThread();
}
}
private boolean handshake() throws IOException {
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
HashMap<String, String> keys = new HashMap<>();
String str;
//Reading client handshake
while (!(str = in.readLine()).equals("")) {
String[] s = str.split(": ");
System.out.println();
System.out.println(str);
if (s.length == 2) {
keys.put(s[0], s[1]);
}
}
//Do what you want with the keys here, we will just use "Sec-WebSocket-Key"
String hash;
try {
hash = new BASE64Encoder().encode(MessageDigest.getInstance("SHA- 1").digest((keys.get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return false;
}
//Write handshake response
out.write("HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + hash + "\r\n"
+ "Origin: http://face2fame.com\r\n"
+ "\r\n");
out.flush();
return true;
}
private byte[] readBytes(int numOfBytes) throws IOException {
byte[] b = new byte[numOfBytes];
socket.getInputStream().read(b);
return b;
}
public void sendMessage(byte[] msg) throws IOException {
System.out.println("Sending to client");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
baos.write(SINGLE_FRAME_UNMASKED);
baos.write(msg.length);
baos.write(msg);
baos.flush();
baos.close();
convertAndPrint(baos.toByteArray());
os.write(baos.toByteArray(), 0, baos.size());
os.flush();
}
public void listenerThread() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
System.out.println("Recieved from client: " + reiceveMessage());
System.out.println("Enter data to send");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
t.start();
}
public String reiceveMessage() throws IOException {
byte[] buf = readBytes(2);
//dont use this byte[] buf2 = readBytes(4);
int extendedsize = 0;
System.out.println("Headers:");
if(!convertAndPrintHeader(buf)){ // This means we detected an extended message
String CaryOverDetectiona = new String("");
byte[] bufadder1 = buf.clone();
byte[] bufadder2 = readBytes(2);
byte[] array1and2 = new byte[bufadder1.length + bufadder2.length];
System.arraycopy(bufadder1, 0, array1and2, 0, bufadder1.length);
System.arraycopy(bufadder2, 0, array1and2, bufadder1.length, bufadder2.length);
for (byte b : array1and2) {
CaryOverDetectiona = (String.format("%02X ", b));
System.out.print(CaryOverDetectiona);
}
int i = ((array1and2[1] & 0xFF) - 0x80);
//int c = ((array1and2[2] & 0xFF) - 0x80);
//System.out.println(c+128);
int j = ((array1and2[3] & 0xFF) - 0x80)+2;
//System.out.println("The size of this uber message is" + j);
extendedsize = i+j;
System.out.println("Extended Size is" + extendedsize);
//System.exit(0);
}
//convertAndPrint(buf2);// Check out the byte sizes
int opcode = buf[0] & 0x0F;
if (opcode == 8) {
//Client want to close connection!
System.out.println("Client closed!");
socket.close();
System.exit(0);
return null;
} else {
int payloadSize = getSizeOfPayload(buf[1]);
if (extendedsize>=126){
payloadSize = extendedsize;}
System.out.println("Payloadsize: " + payloadSize);
buf = readBytes(MASK_SIZE + payloadSize);
System.out.println("Payload:");
convertAndPrint(buf);
buf = unMask(Arrays.copyOfRange(buf, 0, 4), Arrays.copyOfRange(buf, 4, buf.length));
String message = new String(buf);
return message;
}
}
private int getSizeOfPayload(byte b) {
//Must subtract 0x80 from masked frames
int a = b & 0xff;
//System.out.println("PAYLOAD SIZE INT" + a);
return ((b & 0xFF) - 0x80);
}
private byte[] unMask(byte[] mask, byte[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (data[i] ^ mask[i % mask.length]);
}
return data;
}
private boolean convertAndPrintHeader(byte[] bytes) {
StringBuilder sb = new StringBuilder();
String CaryOverDetection = new String();
// We must test byte 2 specifically for this. In the next step we add length bytes perhaps?
//for(int i = 0; i < bytes.length; i++) {
//}
for (byte b : bytes) {
CaryOverDetection = (String.format("%02X ", b));
if (CaryOverDetection.contains("FE")){
return false;
}
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
return true;
}
private void convertAndPrint(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
}
public static void main(String[] args) throws IOException, InterruptedException, NoSuchAlgorithmException {
WebRTCSignal j = new WebRTCSignal();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Write something to the client!");
j.sendMessage(br.readLine().getBytes());
}
}
}
I am trying to take the standard input from the console and send it to my Arduino Uno as plain ASCII.
I get the Input and strip \r\n from it using this code:
String Input = Console.Read().ToString().Replace("\r",string.Empty).Replace("\n",string.Empty);
When I perform doConsole.WriteLine(Input);, it outputs "72" which is correct, but when I do serialPort.Write(Input); the Arduino returns "55", which it does for everything.
What am I doing wrong?
My code for the C# side (host/PC):
String Input = Console.Read().ToString().Replace("\r", string.Empty).Replace("\n",string.Empty);
//Console.WriteLine(Input);
//serialPort.Write(Input);
char[] InputChar = Input.ToCharArray();
serialPort.Write(InputChar,0,1);
//byte[] InputByte = Encoding.ASCII.GetBytes(Input);
//Console.WriteLine(Input);
//serialPort.WriteLine(Input);
Thread.Sleep(25); //Wait 0.025 second.
//***************************************************************//
// Read anything from the serial port. //
//***************************************************************//
numBytes = serialPort.BytesToRead;
for (int i = 0; i < numBytes; i++)
rxPacket[i] = (byte)serialPort.ReadByte();
result = new char[numBytes];
for (int i = 0; i < numBytes; i++)
result[i] = (char)rxPacket[i];
Console.Write("Read this from Arduino:");
Console.WriteLine(result);
Console.WriteLine("press Enter to continue");
Console.ReadKey(); //Read nothing.
And my Arduino sketch:
const int ledPin = 13; // The pin that the LED is attached to.
int incomingByte; // A variable to read incoming serial data into.
void setup() {
// Initialize serial communication:
Serial.begin(9600);
// Initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// Read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// If it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
Serial.print(incomingByte);
}
// If it's an L (ASCII 76), turn off the LED:
else if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
Serial.print(incomingByte);
}
else{
Serial.print(incomingByte);
}
}
}
Edit: changed the code to the following. Still no luck; I am getting same reply.
String Input = Console.Read().ToString().Replace("\r",string.Empty).Replace("\n",string.Empty);
Console.Write(Input,0,1);
//serialPort.Write(Input);
byte[] inputByte = Encoding.ASCII.GetBytes(Input);
serialPort.Write(inputByte,0,1);
Well, I looked it up... As it turns out, ASCII code 55 = 7.
7 is the first digit of 72.
Hmm, so perhaps your sending decimal numbers to the Arduino here and the Arduino sees a 7 first. May I suggest to convert your byte and send it as a byte (a byte can only contain 0..255), but it is a single ASCII code.
Maybe for the Arduino to think about, but maybe it is not related to this. Instead of
int incomingByte; // ints are made of 2 bytes an int isn't an incomming byte
try
Byte incomingByte;
So I managed to get it working
Basically, converting it to a byte took me a while to work out.
this is the code I ended up with
String Input = Console.Read().ToString().Replace("\r", string.Empty).Replace("\n",string.Empty);
Console.Write(Input,0,1);
byte[] inputByte = new byte[1];
inputByte[0] = Convert.ToByte(Input);
serialPort.Write(inputByte, 0, 1);
//byte[] inputByte = Encoding.ASCII.GetBytes(Input);
//serialPort.Write(inputByte,0,2);
//String num = inputByte.ToString();
//serialPort.WriteLine(num);
//Console.WriteLine(Input);
//serialPort.Write(InputByte,0,1);
Thread.Sleep(25); //Wait 0.025 second.
//***************************************************************//
// Read anything from the serial port. //
//***************************************************************//
numBytes = serialPort.BytesToRead;
for (int i = 0; i < numBytes; i++)
rxPacket[i] = (byte)serialPort.ReadByte();
result = new char[numBytes];
for (int i = 0; i < numBytes; i++)
result[i] = (char)rxPacket[i];
Console.Write("Read this from Arduino:");
Console.WriteLine(result);
Console.WriteLine("press Enter to continue");
Console.ReadKey(); //Read nothing.
Seems to work Perfectly now.