Guys I am a not a pro and some of you might think its a basic question but I really need help as I am on deadline to complete my Final Year Project. So here is what I am doing I found two codes a server and a client in which client sends Images to the server over some specified socket. The code is written in C++ and is for Linux. What I am looking for is a way to convert Server side of the code to C# so that I can run it on Windows and client must remain in C++ to be run on Linux. Both these codes are below for referencing.
Server:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main ( int agrc, char *argv[] )
{
/******** Program Variable Define & Initialize **********/
int Main_Socket; // Main Socket For Server
int Communication_Socket; // Socket For Special Clients
int Status; // Status Of Function
struct sockaddr_in Server_Address; // Address Of Server
struct sockaddr_in Client_Address;// Address Of Client That Communicate with Server
int Port;
char Buff[100] = "";
Port = atoi(argv[2]);
printf ("Server Communicating By Using Port %d\n", Port);
/******** Create A Socket To Communicate With Server **********/
Main_Socket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( Main_Socket == -1 )
{
printf ("Sorry System Can Not Create Socket!\n");
}
/******** Create A Address For Server To Communicate **********/
Server_Address.sin_family = AF_INET;
Server_Address.sin_port = htons(Port);
Server_Address.sin_addr.s_addr = inet_addr(argv[1]);
/******** Bind Address To Socket **********/
Status = bind ( Main_Socket, (struct sockaddr*)&Server_Address, sizeof(Server_Address) );
if ( Status == -1 )
{
printf ("Sorry System Can Not Bind Address to The Socket!\n");
}
/******** Listen To The Port to Any Connection **********/
listen (Main_Socket,12);
socklen_t Lenght = sizeof (Client_Address);
int yx=1;
char bs[10000] = "??";
while (1)
{
Communication_Socket = accept ( Main_Socket, (struct sockaddr*)&Client_Address, &Lenght );
if (!fork())
{
FILE *fp=fopen("recv.jpg","w");
while(1)
{
char Buffer[10000]="";
if (recv(Communication_Socket, Buffer, sizeof(Buffer), 0))
{
if ( strcmp (Buffer,bs) == 0 )
{
break;
}
else
{
fwrite(Buffer,sizeof(Buffer),1, fp);
printf("\n%d) DATA RECIEVED", yx);
yx=yx+1;
}
}
}
fclose(fp);
send(Communication_Socket, "ACK" ,3,0);
printf("\nACK Send\n");
exit(0);
}
}
return 0;
}
Client:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main ( int agrc, char *argv[] )
{
int Socket;
struct sockaddr_in Server_Address;
Socket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( Socket == -1 )
{
printf ("Can Not Create A Socket!");
}
int Port ;
Port = atoi(argv[2]);
Server_Address.sin_family = AF_INET;
Server_Address.sin_port = htons ( Port );
Server_Address.sin_addr.s_addr = inet_addr(argv[1]);
if ( Server_Address.sin_addr.s_addr == INADDR_NONE )
{
printf ( "Bad Address!" );
}
connect ( Socket, (struct sockaddr *)&Server_Address, sizeof (Server_Address) );
FILE *in = fopen("a.jpg","r");
char Buffer[10000] = "";
char bs[10000] = "??";
int len;
int yx=1;
while ((len = fread(Buffer,sizeof(Buffer),1, in)) > 0)
{
send(Socket,Buffer,sizeof(Buffer),0);
printf("\n %d) HELLO DOING IT", yx);
yx = yx + 1;
}
send(Socket,bs,sizeof(Buffer),0);
char Buf[BUFSIZ];
recv(Socket, Buf, BUFSIZ, 0);
if ( strcmp (Buf,"ACK") == 0 )
{
printf("\nRecive ACK\n");
}
close (Socket);
fclose(in);
return 0;
}
P.S. None of these are my own codes they are as I found them on the Internet but they are working perfectly.
Translating socket code from C++ to C# is quite straightforward. Your can do it quite quickly with a near line by line translation. That doesn't take advantage of C# features, but that's easy.
The C# class Socket (documentation) expose the underlying socket API, and you can find the C++ C# equivalent Socket() (constructor), .Bind(), .Listen(), .Accept(), .Receive(), .Send().
For the file IO, you have the File and FileStream classes.
Related
I am writing a c#application which communicates with a device c application.
I am trying to write data from the c# application to c application over the serial port and vice versa.
I am trying to write some sample data using the following code.
C#
using PORT = System.IO.Port.SerialPort;
PORT p = new PORT("COM4", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
string data="HELLO";
//String to byte[] conversion
byte[] byt_buff = new byte[data.Length];
byt_buff = Encoding.ASCII.GetBytes(data);
p.Open();
p.DiscardOutBuffer();
p.Write(byt_buff, 0, byt_buff.Length);
p.Close();
The c application running on the device has the following code.
C
#include<stdio.h>
#include <poll.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdint.h>
#include<string.h>
#define USB_DEV_NODE "usb.dat"
#define MAX_SIZE 20
int main()
{
int fd;
int ret_poll;
int ret_read;
struct pollfd pollfd;
char buf[MAX_SIZE];
int i = 0;
pollfd.events = POLLIN;
fd = open(USB_DEV_NODE, O_RDWR | O_NOCTTY);
pollfd.fd = fd;
while (1)
{
ret_poll = poll( &pollfd, 1, -1);
if( ret_poll == -1 )
{
printf("Gpio_poll poll failed\r\n");
close(fd);
}else{
if (pollfd.revents & POLLIN )
{
ret_read = read(fd, buf, MAX_SIZE);
buf[ret_read]=0;
if(ret_read > 0)
{
for(i=0;i<ret_read ; i++)
{
printf("BUF[%d]=%c\n",i,buf[i]);
}
}
}
}
}
return 0;
}
But I am failing to receive the data written as byte[],No data is recieved. Instead if I write data as a string using p.WriteLine("HELLO"); it will be recieved. Please help.
I'm working on Client-Server application on Windows. Everything perfect running but when I want to send text (ex: Hello Dude) from C# client to C server then it send just "p" character. I dont know why? Thank you.
C# - Client Codes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string ip, nick;
int port;
Console.Write("Nick Giriniz : ");
nick = Console.ReadLine();
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("192.168.1.37");
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 5150);
soc.Connect(remoteEP);
NetworkStream ag = new NetworkStream(soc);
BinaryReader okuyucu = new BinaryReader(ag);
baslangic:
byte[] byData = System.Text.Encoding.ASCII.GetBytes("Hi Dude");
soc.Send(byData);
Console.Write("Wait for answer");
string reply = okuyucu.ReadString();
Console.Write(reply );
goto baslangic;
}
}
}
C - Server
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#define DEFAULT_PORT 5150
#define AZAMIUZUNLUK 1024
int g_port = DEFAULT_PORT; // Gelen Istekleri Dinleyecek Port
char g_szAddress[128]; // Gelen Istekleri Dinleyecek Arayuz
DWORD WINAPI ClientThread(LPVOID lpParam) //Dword = 32 bit isaretsiz tamsayi.
{
SOCKET sock =(SOCKET)lpParam;
int ret;
char gelenverix[512];
char str[AZAMIUZUNLUK];
for (;;) {
ret = recv(sock, gelenverix, 512, 0); //recv(socket,xxxxx, uzunluk, bayrak);
if (ret == 0)
break;
if (ret == SOCKET_ERROR) {
fprintf(stderr, "Mesajlasma Sona Erdi\n", WSAGetLastError());
break;
}
if (gelenverix == '\x1b')
break;
putchar(gelenverix);
}
return 0;
}
int main(void)
{
WSADATA wsd;
SOCKET sListen,sClient;
int addrSize;
HANDLE hThread;
DWORD dwThreadId;
struct sockaddr_in local, client;
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) {
fprintf(stderr, "WSAStartup yuklemesi basarisiz!\n");
return 1;
} else {
fprintf(stderr, "WSAStartup Yuklendi!\n");
}
sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (sListen == SOCKET_ERROR) {
fprintf(stderr, "Socket Baglantisi Basarisiz!\n", WSAGetLastError());
return 1;
} else {
fprintf(stderr, "Socket Baglantisi Basarili!\n", WSAGetLastError());
}
local.sin_addr.s_addr = htonl(INADDR_ANY); // ip adresimi kullan
local.sin_family = AF_INET; // adres ailesi Arpa Internet protokolu
local.sin_port = htons(g_port); // default port numarasi
if (bind(sListen, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR) {
fprintf(stderr, "bind() failed: %d\n", WSAGetLastError());
return 1;
}
listen(sListen, 8); //8 - cagri kurugunda izin verilen baglanti sayisi
for (;;) {
addrSize = sizeof(client);
sClient = accept(sListen, (struct sockaddr *) &client, &addrSize);
if (sClient == INVALID_SOCKET) {
fprintf(stderr, "accept() failed: %d\n", WSAGetLastError());
break;
}
fprintf(stderr, "Accepted client: %s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)sClient, 0, &dwThreadId);
if (hThread == NULL) {
fprintf(stderr, "CreateThread() failed: %d\n", GetLastError());
break;
}
CloseHandle(hThread);
}
closesocket(sListen);
WSACleanup();
return 0;
}
putchar(gelenverix) should make your compiler yell in pain, as it expects a char and the code passes it a char*.
Use puts() instead. Also make sure gelenverix is 0-terminated beforehand.
ret = recv(sock, gelenverix, 512 - 1, 0); /* One less as you need space to 0-terminate the buffer. */
if (ret == 0)
break;
if (ret == SOCKET_ERROR) {
...
break;
}
gelenverix[ret] = '\0'.
puts(gelenverix);
Or just do
for (size_t i = 0; i < ret; ++i)
{
putchar(gelenverix[i]);
}
I have two programs written in c++ and c#.I want to establish a two way communication using named-pipe between them. The C# client program can be connected to the named-pipe created by c++ server program.But nothing received in both ends.
Here is the c++ part (Server):
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#define UNICODE
using namespace std;
HANDLE hnamedPipe = INVALID_HANDLE_VALUE;
BOOL Finished =false;
HANDLE hThread = NULL;
unsigned long __stdcall CS_RcvThr(void * pParam) ;
int main(int argc, char **argv)
{
hnamedPipe = CreateNamedPipe(
"\\\\.\\pipe\\vikeyP",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE|
PIPE_READMODE_MESSAGE|
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
1024,
1024,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
if(hnamedPipe == INVALID_HANDLE_VALUE)
{
cout << "Failed" << endl;
}
while (true)
{
cout<< "Waiting for client"<< endl;
if(!ConnectNamedPipe(hnamedPipe,NULL))
{
if(ERROR_PIPE_CONNECTED != GetLastError())
{
cout << "FAIL"<< endl;
}
}
else
{
cout<<"Connected!"<<endl;
hThread = CreateThread( NULL, 0, &CS_RcvThr, NULL, 0, NULL);
if(hThread) cout<<"read thread created"<<endl; else cout<<"cant crat rd thed\n";
break;
}
}
while(1)
{
cout<<"lst loop"<<endl;
//Send over the message
char chResponse[] = "hello\n";
DWORD cbResponse,cbWritten;
cbResponse = sizeof(chResponse);
if (!WriteFile(
hnamedPipe,
chResponse,
cbResponse,
&cbWritten,
NULL))
{
wprintf(L"failiure w/err 0x%08lx\n",GetLastError);
}
cout<<"Sent bytes :)" << endl;
Sleep(10);
}
}
unsigned long __stdcall CS_RcvThr(void * pParam) {
BOOL fSuccess;
char chBuf[100];
DWORD dwBytesToWrite = (DWORD)strlen(chBuf);
DWORD cbRead;
int i;
while (1)
{
fSuccess =ReadFile( hnamedPipe,chBuf,dwBytesToWrite,&cbRead, NULL);
if (fSuccess)
{
printf("C++ App: Received %d Bytes : ",cbRead);
for(i=0;i<cbRead;i++)
printf("%c",chBuf[i]);
printf("\n");
}
if (! fSuccess && GetLastError() != ERROR_MORE_DATA)
{
printf("Can't Read\n");
if(Finished)
break;
}
}
}
Here is the C# part (Client):
private Thread vikeyClientThread;
public void ThreadStartClient()
{
Console.WriteLine("Thread client started ID ={0} name = {1} " ,
Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.Name);
using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "vikeyP"))
{
// The connect function will indefinately wait for the pipe to become available
// If that is not acceptable specify a maximum waiting time (in ms)
Console.WriteLine("Connecting to ViKEY server...");
pipeStream.Connect();
Console.WriteLine("Connected :)");
//Write from client to server
StreamWriter sw = new StreamWriter(pipeStream);
while (true)
{
//Read server reply
StreamReader sr = new StreamReader(pipeStream);
string temp = "";
sw.WriteLine(System.DateTime.Now);
byte[] c = new byte[200];
temp = sr.ReadLine();
pipeStream.Read(c, 0, c.Length);
Console.WriteLine("RX =:{0}", Encoding.UTF8.GetString(c, 0, c.Length));
Thread.Sleep(500);
}
}
Console.WriteLine("Vikey pipe Closed");
Console.WriteLine("Thread with ID ={0} name = {1} is closed.",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name);
}
You've set the server side up as a message type vs byte type. If you want to read an arbitrary number of bytes, you'll need to use a byte type named pipe.
You're wrapping the stream in 2 objects one StreamReader and one StreamWriter. Don't do that, just use a Stream. You're trying to read by line, don't do that either. Instead send the number of bytes to read followed by the bytes. On the client side you'll read the byte count then create a buffer big enough then read. If it's text data you then would use an encoder (probably ASCII) to translate it back into a C# string.
Your while(true) should instead detect when the server has closed the pipe.
You should probably look into using an asynchronous named pipe.
This is the 1st time am posting my query. I am in need of help. Any help is appreciated.
As i agree that i have given my prob as long story. But am sorry i am not getting how to make it short and my intention is give complete information regarding my prob.
Problem :
I have to communicate between two laptops using USB-to-Serial adapter on windows platform. I have written 2 programs one for sending and another for receiving. Programs were written in both C and C# programming languages.
Using C language :
I am able to successfully communicate using C-Programs mentioned below. But the problem is speed. It takes around 1 hour(60min) for just to pass 150MB. Anyone plz help me in improving the performance of this programs or you may suggest me other approaches which is robust and give high performance. I also mention some comments along with programs for self understanding.
Sender File on laptop with serial port :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#define COM1 0
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status, DONE = FALSE,i=0;
char c;
FILE *fp,*fp1;
unsigned long count = 0,shiftcount = 0;
clrscr();
fp = fopen("C:/TC/pic.jpg","rb"); //opened for reading actual content
fp1 = fopen("C:/TC/pic.jpg","rb"); //opened for reading the size of file
fseek(fp1,0L,2);
count = ftell(fp1) + 1; // file size
bioscom(0, SETTINGS, COM1); // initializing the port
printf("No. of Characters = %lu\n",count);
// since bioscom function can send or receive only 8bits at a time, am sending file size in
4 rounds so that we can send at max of 4GB file.
bioscom(1,count,COM1); // sneding 1st lower 8bits
bioscom(1,count>>8,COM1); // sending 2nd set of lower 8bits
bioscom(1,count>>16,COM1); // sending 3rd set of lower 8bits
bioscom(1,count>>24,COM1); // sending upper 8 bits
cprintf("... BIOSCOM [ESC] to exit ...\n");
while (!DONE)
{
status = bioscom(3, 0, COM1);// get the status of port
//printf("%d",status);
if (status & DATA_READY) //checks if data is ready
{
out = bioscom(2, 0, COM1); // receives the ack
if(!feof(fp))
{
c = fgetc(fp); //read character by character from file
bioscom(1,c,COM1);//send character to receiver
putch(c);//display
}
}
//to interrupt
if (kbhit())
{
if ((in = getch()) == '\x1B')
DONE = TRUE;
}
}
fclose(fp);
return 0;
}
Receiving file on laptop with USB port :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#define COM4 3
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status;
char c;
FILE *fp;
unsigned long shiftcount1=0,shiftcount2=0,shiftcount3=0,shiftcount4=0;
unsigned long count = 0, DONE = 1;
clrscr();
fp = fopen("C:/TC/pic1.jpg","wb");// file opened for writing
bioscom(0, SETTINGS, COM4);//initialize tyhe port
cprintf("... BIOSCOM [ESC] to exit ...\n");
//receives all the 32 bits of file size sent from sender
shiftcount1 = bioscom(2,0,COM4);
shiftcount2 = bioscom(2,0,COM4);
shiftcount3 = bioscom(2,0,COM4);
shiftcount4 = bioscom(2,0,COM4);
//send an ack
bioscom(1,'x',COM4);
count = shiftcount1 | (shiftcount2<<8) | (shiftcount3<<16) | (shiftcount4<<24);
printf("shift4 = %lu\tshift3 = %lu\tshift2 = %lu\tshift1 = %lu\n",shiftcount4,shiftcount3,shiftcount2,shiftcount1);
printf("File Size = %lu\n",count);
//loop till the size of the file
while (DONE < count)
{
status = bioscom(3, 0, COM4);// check the status
// printf("%d",status);
if (status & DATA_READY)//check for data ready at the port
{
out = bioscom(2, 0, COM4);//receive the data
DONE++;
fputc(out,fp);
putch(out);
bioscom(1,'x',COM4);//send an ack
}
if (kbhit())
{
if ((in = getch()) == '\x1B')
break;
}
}
fclose(fp);
return 0;
}
Sender file on laptop with USB port:
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#include<dos.h>
#include<stdlib.h>
#include<time.h>
#define RTS 0x02
#define COM1 0
#define COM4 3
#define CURRCOM COM4
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status, DONE = FALSE,nextfile = 1;
char c;
FILE *fp,*fp1;
unsigned long count = 0,shiftcount = 0;
clock_t start,end;
start = clock();
clrscr();
fp = fopen("C:/TC/pic.jpg","rb");
fp1 = fopen("C:/TC/pic.jpg","rb");
fseek(fp1,0L,2);
count = ftell(fp1) + 1;
bioscom(0, SETTINGS, CURRCOM);
/* while(!feof(fp1))
{
c = fgetc(fp1);
count++;
} */
printf("No. of Cheracters = %lu\n",count);
bioscom(1,count,CURRCOM);
bioscom(1,count>>8,CURRCOM);
bioscom(1,count>>16,CURRCOM);
bioscom(1,count>>24,CURRCOM);
cprintf("\n... BIOSCOM [ESC] to exit ...\n");
while (!DONE)
{
status = bioscom(3, 0, CURRCOM);
if (status & DATA_READY)
{
out = bioscom(2,0,CURRCOM);
if(!feof(fp))
{
c = fgetc(fp);
bioscom(1,c,CURRCOM);
putch(c);
}
}
if (kbhit())
{
if ((in = getch()) == '\x1B')
DONE = TRUE;
}
}
fclose(fp);
end = clock();
printf("\nTotal time = %d\n",(end - start)/CLK_TCK);
return 0;
}
Receiver file on laptop with serial port :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#include<time.h>
#define COM1 0
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status;
char c;
FILE *fp;
int y = 0,esc;
unsigned long count=0,shiftcount1 = 0,shiftcount2 = 0,shiftcount3 = 0,shiftcount4 = 0, DONE = 1;
clock_t start,end;
start = clock();
clrscr();
fp = fopen("C:/TC/pic1.jpg","wb");
bioscom(0, SETTINGS, COM1);
cprintf("... BIOSCOM [ESC] to exit ...\n");
shiftcount1 = bioscom(2,0,COM1);
shiftcount2 = bioscom(2,0,COM1);
shiftcount3 = bioscom(2,0,COM1);
shiftcount4 = bioscom(2,0,COM1);
bioscom(1,'x',COM1);
count = shiftcount1 | (shiftcount2<<8) | (shiftcount3<<16) | (shiftcount4<<24);
printf("shift4 = %lu\tshift3 = %lu\tshift2 = %lu\t shift1 = %lu\n",shiftcount4,shiftcount3,shiftcount2,shiftcount1);
printf("file size = %lu\n",count);
while (DONE < count)
{
status = bioscom(3, 0, COM1);
//printf("%d",status);
if (status & DATA_READY)
{
out = bioscom(2, 0, COM1);
DONE++;
fputc(out,fp);
putch(out);
bioscom(1,'x',COM1);
}
if (kbhit())
{
if ((in = getch()) == '\x1B')
break;
}
}
fclose(fp);
end = clock();
printf("\nTotal time = %f\n",(end - start)/CLK_TCK);
return 0;
}
The above 4 programs behaves as, sender send a character and receives an ack for every character. I have followed this approach, bcoz other approaches were not working fine (in the sense the complete data is not sent, the amount of data sent is not judgeable, bcoz it will different every tym). when i used this approach it worked fine.
Using C# language :
Below two programs are written in C# using visual studio. I have used SerilaPort class , its properties and methods for communication. Using this, am able to communicate text and xml files on both the sides successfully.Also image files with .jpg extention, can be transferred from USB to serial end withot any loss of data(successful transmission), but if i transfer from serial to usb end, am able receive image with some data loss, even with the data loss am able to see the image.
Sender file on laptop with serial port :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Threading;
namespace Communication
{
class Program
{
static void Main(string[] args)
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
//Thread readThread = new Thread(Read);
FileStream fs = new FileStream("C:/text.xml", FileMode.Open);
//StreamReader sr = new StreamReader(fs);
BinaryReader br = new BinaryReader(fs);
// Create a new SerialPort object with default settings.
SerialPort _serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = "COM1";
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
bool _continue = true;
//readThread.Start();
int len = (int)fs.Length;
char[] data = new char[len+1];
br.Read(data, 0, len);
for (int i = 0; i < len+1; i++)
{
_serialPort.Write(data, i, 1);
//Console.Write(data,i,1);
}
br.Close();
fs.Close();
_serialPort.Close();
}
}
}
Receiver file on laptop with USB port :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Threading;
using System.Collections;
namespace Communication
{
class Program
{
static void Main(string[] args)
{
SerialComm comm = new SerialComm();
comm.Init();
comm.ReadSerial();
comm.WriteToFile();
comm.ResClose();
Console.ReadKey();
}
}
class SerialComm
{
FileStream fs = null;
BinaryWriter file = null;
ArrayList al = null;
public Boolean Init()
{
if (fs == null)
{
fs = new FileStream("C:/text1.txt", FileMode.OpenOrCreate);
}
if (file == null)
{
file = new BinaryWriter(fs);
}
if (al == null)
{
al = new ArrayList();
}
return true;
}
public void ResClose()
{
file.Close();
fs.Close();
}
public Boolean ReadSerial()
{
SerialPort port;
StreamWriter sw;
ConsoleKeyInfo ck;
port = new SerialPort();
port.PortName = "COM4";
port.BaudRate = 115200;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.Open();
port.BaseStream.Flush();
port.DiscardInBuffer();
int c = 1;
while (c != 0)
{
c = port.ReadByte();
al.Add((byte)c);
}
return true;
}
public void WriteToFile()
{
int i = 0;
byte[] message = al.ToArray(typeof(byte)) as byte[];
file.Write(message, 0, message.Length - 1);
}
}
}
Please help me.
Thanks in advance.
Transmission speed:
Serial ports are simple, not fast. I am assuming that you are using 230kbps which is already more than many hardware can handle. Compression is only thing that might help, but compressing already compressed data (like .mp3) won't help much.
Data loss:
Serial ports are simple, not robust. Data loss is common, and only thing you can do about it is to have protocol to detect errors on incoming frames, and have ability to retry send if there is an error.
Conclusion:
Use TCP/IP instead.
Way too long a question. I've found only one actual question, and that's the performance bit.
Just use Ethernet or WiFi. "Serial port" (you probably mean RS-232) speeds are low. 0.1 Mbit/second is considered fast by RS-232 standards. You clock 1200 Mbit/3600 seconds, which is 0.3 Mbit/second. That is ultra-fast. I'm in fact surprised that you achieve that, your C# program is explicitly setting the speed to 0.1 Mbit/second.
I have a server written in C# using a TcpClient and streams. When I try to connect to it and receive data with a C++ application using Winsock, I can receive the data but it has the data but it also displays a bunch of other data. By the way I'm printing to buffer to the console using cout.
If you want to see what the server is supposed to send, go to http://onenetworks.us:12345. There the server will send you a string. For me it sends "16READY" Which is what I'm trying to get my client to only read.
Here's my code, I copied a working code file off of the MSDN page.
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "12345"
int main() {
//----------------------
// Declare and initialize variables.
WSADATA wsaData;
int iResult;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
char *sendbuf = "";
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "199.168.139.14" );
clientService.sin_port = htons( 12345 );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
printf("Unable to connect to server: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
std::cout << recvbuf <<std::endl;
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while(iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
std::cin.ignore();
//return 0;
}
Print only the characters received, not the entire buffer posted. iResult will contain the length of the data received:
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
{
printf("Bytes received: %d\n", iResult);
std::cout << std::string(recvbuf, recvbuf+iResult) <<std::endl;
}
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
The length of your buffer is set to DEFAULT_BUFLEN, so whatever you receive through the socket has that length. you can loop through every char of it, until a value of 0 (or '\0') is found.
You could do something like this:
...
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recvbuf[iResult] = 0; // add this to zero terminate the receive buffer
std::cout << recvbuf <<std::endl;
...
(of course it assumes iResult is lesser than DEFAULT_BUFLEN)