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]);
}
Related
I have a TCPListener in C# and the client in Unix C. I use TcpClient.Client.SendFile for transmitting a file to client socket in Unix and it works fine for plain txt file. It fails to produce the full file on the unix end, when I send JPEG files. Any Idea?
C# code part
============
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(10001);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom).TrimEnd('\0');
Console.WriteLine(" >> Data from client - " + dataFromClient +" Length "+ dataFromClient.Length);
string a1 = "C:\\MRTD\\PICTURE\\abc.jpg";
clientSocket.Client.SendFile(a1);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
}
Unix C code to read the file
============================
char *tcp_recv( int id_type )
{
register int nbytes;
static char readbuf[MAXLINE];
static char tempbuf[980000];
int ngot = 0, bulk_data=0, p_read_val;
char * x, * y, * z, *j, *k, *x1, *bar;
char bulk_buf[180000], tempstr1[180000] , fstr[40], termtor[40];
int fd_ready;
fd_set read_fds; /* Read file descriptors */
int fd_port = gfd_sock;
struct timeval timeout;
timeout.tv_sec = 3600;
timeout.tv_usec = 0;
while (TRUE)
{
FD_ZERO( &read_fds );
FD_SET( fd_port, &read_fds );
strcpy(fstr,"FAIL");
if((fd_ready = select(fd_port+1,&read_fds,NULL,NULL,&timeout))< 0)
{
if( errno == EINTR ) { continue; }
logmsg("ERROR select() returned errno %d", errno );
logmsg("Select error waiting for packet." );
return fstr;
}
else if( fd_ready == 0 )
{
logmsg("Timeout waiting for packet.");
strcpy(fstr,"TIMEOUT");
return fstr;
}
memset( readbuf, 0x00, sizeof( readbuf ));
memset( br_kde, 0x00, sizeof( br_kde ));
if((nbytes = read( fd_port, readbuf, sizeof(readbuf)-1 )) < 0 )
{
logmsg( "tcp_recv: nbytes %d, errno %d, %s", nbytes, errno, strerror( errno ) );
if (errno == EINTR || errno == EAGAIN )
{
errno = 0;
continue; /* assume SIGCLD */
}
else
{
/*
* connection failer.
*/
logcon( "Desko connection failed. Pier link is DOWN!" );
logmsg( "Desko connection failed. Pier link is DOWN!" );
close_files();
exit (1);
break;
} /* end else if */
}
else
{
logmsg("tcp_recv: readbuf is %s, bytes %d", readbuf, nbytes);
strcat(tempbuf, readbuf);
logmsg("tempbuf is %s", tempbuf );<== full file listing is missing in case of JPEG
}
return tempbuf;
}
}
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.
I have a small program to receive UPD Packets. I have some bit problem in receiving packets . I actually need to revce packets by id for example "position (packet id: 196) , Location :187 etc" With my code i get some data but i dont know how to find the id and how to get real data inside the packet.
Packet Header
|SYNC Byte|SYNC Byte|Data Length|Identifier|Data Bytes|Checkssum|
|1(0x24) |2(0x40) |Byte |Bye | |Byete |
Field :Sync Bytes SIZE: 2 Bytes
Field :Data Length SIZE: 1 Byte
Field :Packet Identifier SIZE: 1 byte
Field :Data SIZE: 0-255 bytes
Field :Checksum SIZE: 1 byte
enter code here
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace SimpleUdpReciever
{
class pProgram
{
static void Main(string[] args)
{
int localPort = 18006;
IPEndPoint remoteSender = new IPEndPoint(IPAddress.Any, 0);
bool flag = false;
for (int i = 0; i < args.Length; i++)
{
string cmd = args[i];
string value;
int tempInt;
IPAddress tempAddress;
switch (cmd)
{
case "-lp":
value = GetValue(args, ref i);
if (int.TryParse(value, out tempInt))
localPort = tempInt;
break;
case "-rp":
value = GetValue(args, ref i);
if (int.TryParse(value, out tempInt))
remoteSender.Port = tempInt;
break;
case "-rh":
value = GetValue(args, ref i);
if (IPAddress.TryParse(value, out tempAddress))
remoteSender.Address = tempAddress;
else if (int.TryParse(value, out tempInt) && tempInt == 0)
remoteSender.Address = IPAddress.Any;
break;
case "-?":
default:
PrintHelpText();
flag = true;
break;
}
}
// Exit application after help text is displayed
if (flag)
return;
// Create UDP client
UdpClient client = new UdpClient(localPort);
UdpState state = new UdpState(client, remoteSender);
// Start async receiving
client.BeginReceive(new AsyncCallback(DataReceived), state);
// Wait for any key to terminate application
Console.ReadKey();
client.Close();
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)((UdpState)ar.AsyncState).c;
IPEndPoint wantedIpEndPoint = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = c.EndReceive(ar, ref receivedIpEndPoint);
bool isRightHost = (wantedIpEndPoint.Address.Equals(receivedIpEndPoint.Address)) || wantedIpEndPoint.Address.Equals(IPAddress.Any);
bool isRightPort = (wantedIpEndPoint.Port == receivedIpEndPoint.Port) || wantedIpEndPoint.Port == 0;
if (isRightHost && isRightPort)
{ string test5 = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("test5 = {0}", test5);
}
// Restart listening for udp data packages
c.BeginReceive(new AsyncCallback(DataReceived), ar.AsyncState);
}
private static string GetValue(string[] args, ref int i)
{
string value = String.Empty;
if (args.Length >= i + 2)
{
i++;
value = args[i];
}
return value;
}
private static void PrintHelpText()
{
Console.WriteLine("Simple Udp Receiver is an application that prints incoming data to screen.");
Console.WriteLine("Data is converted to ASCII before printing.");[![enter image description here][1]][1]
Console.WriteLine("Command switches:");
Console.WriteLine("-? : Displays this text.");
Console.WriteLine("-lp : Set local receiving port. \"-lp 4001\" Default: 11000");
Console.WriteLine("-rp : Set remote sender port. \"-rp 4001\" Default: 0 (Any port)");
Console.WriteLine("-rh : Set remote sender ip. \"-rh 192.168.1.10\" Default: 0 (Any ip)");
Console.WriteLine("\n Example of usage:\nSimpleUdpReciver.exe -lp 11000 -rh 192.168.10.10 -rp 4001");
}
}
}
Out put Looks like this whiole running this program : $# za� �X
�� �
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)
I am trying to write an app in C to communication with a device through a COM port.
I am able to send data using Docklight (hyper terminal like program) with the following settings and I can verify that I am receiving it through Itronix LogicPort Logic Analyzer.
Baud rate:9600
Parity:None
Byte Size:8
Stop bits:1
I am having 2 problems with my C program:
1) sometimes CreateFile returns INVALID_HANDLE_VALUE
and the other problem I can't seem to get by is that
GetCommState()
SetCommState()
SetCommTimeouts()
always return ERROR_INVALID_PARAMETER 87 (0x57)
Since I couldn't get past this problem, I tried a program in C# and that works just fine, but my program must be in C to communicate with the rest of my code. This program also communicates with other programs in C through sockets.
in Device Manager the device I want to talk to is listed as COM6 under Ports(COM & LPT)
any help would be appreciated!
Below is the code for both programs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
byte[] TxBuffer = new byte[20];
SerialPort CommPort = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CommPort.Open();
TxBuffer[0] = (byte)'|';
TxBuffer[1] = 0;
TxBuffer[2] = 0;
TxBuffer[3] = 0;
TxBuffer[4] = 1;
TxBuffer[5] = 100;
TxBuffer[6] = 1;
TxBuffer[7] = 6;
TxBuffer[8] = (byte)'|';
TxBuffer[9] = 1;
}
private void button1_Click(object sender, EventArgs e)
{
CommPort.Write(TxBuffer, 0, 10);
}
}
}
and the C code is:
somewhere
struct serial_dev {
HANDLE hSerial;
};
struct serial_dev sdev; //global
//somewhere in main
if (init_serial(&sdev, com_file) == -1)
return -1;
write_ser(&sdev, buffer, buf_size);
close_serial(&sdev);
// in serial.c
int init_serial(struct serial_dev *sdev, char *port_name)
{
DCB dcbSerialParams;
COMMTIMEOUTS timeouts;
int error = 0;
memset(&dcbSerialParams, 0, sizeof(dcbSerialParams));
memset(&timeouts, 0, sizeof(timeouts));
sdev->hSerial = CreateFile("COM6", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (sdev->hSerial == INVALID_HANDLE_VALUE)
{
error = GetLastError();
close_serial(sdev);
fprintf(stderr, "error: could not open serial port (error:%d)\n", error);
return -1;
}
memset(&dcbSerialParams, 0, sizeof(dcbSerialParams));
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(sdev->hSerial, &dcbSerialParams))
{
close_serial(sdev);
error = GetLastError();
fprintf(stderr, "error: could not get serial port state (%d)\n", error);
return -1;
}
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(sdev->hSerial, &dcbSerialParams))
{
close_serial(sdev);
error = GetLastError();
fprintf(stderr, "error: could not set serial port state (%d)\n", error);
return -1;
}
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 200;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(sdev->hSerial, &timeouts))
{
close_serial(sdev);
error = GetLastError();
fprintf(stderr, "error: could not set serial port timeouts (%d)\n", error);
return -1;
}
return 0;
}
void close_serial(struct serial_dev *sdev)
{
CloseHandle(sdev->hSerial);
}
int write_ser(struct serial_dev *sdev, void *buf, size_t len)
{
DWORD written;
BOOL success;
success = WriteFile(sdev->hSerial, buf, len, &written, NULL);
if(!success || written == 0)
{
printf("error writing to serial\n");
return -1;
}
printf("writing to serial OK!\n");
return written;
}
guys I figured it out... I removed the "UNICODE" and "_UNICODE" preprocessor macros from my project settings and set it to "Not Set" found answer here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/1a77c595-10a5-4f14-8512-c67535c53a08/