I don't know if I should reply to my previous question or I should to ask a new one
For a project for my university I have to create a client/server application where the client and the server communicate through sockets and the client streams WAV files from the server using DirectSound API
the server and the client communication through sockets its working but when I am choose which file to play I am getting this message:
// Initialize DirectSound
IDirectSound8* dsound;
if (DirectSoundCreate8(NULL, &dsound, NULL) != DS_OK) {
std::cout << "Error initializing DirectSound" << std::endl;
closesocket(socket_client);
WSACleanup();
return 1;
}
if (dsound->SetCooperativeLevel(GetDesktopWindow(), DSSCL_PRIORITY) != DS_OK) {
std::cout << "Error setting cooperative level" << std::endl;
dsound->Release();
closesocket(socket_client);
WSACleanup();
return 1;
}
// Create primary buffer
DSBUFFERDESC primary_buffer_desc;
memset(&primary_buffer_desc, 0, sizeof(primary_buffer_desc));
primary_buffer_desc.dwSize = sizeof(primary_buffer_desc);
primary_buffer_desc.dwFlags = DSBCAPS_PRIMARYBUFFER;
IDirectSoundBuffer* primary_buffer;
if (dsound->CreateSoundBuffer(&primary_buffer_desc, &primary_buffer, NULL) != DS_OK) {
std::cout << "Error creating primary buffer" << std::endl;
dsound->Release();
closesocket(socket_client);
WSACleanup();
return 1;
}
// Set primary buffer format
WAVEFORMATEX primary_buffer_format;
memset(&primary_buffer_format, 0, sizeof(primary_buffer_format));
primary_buffer_format.wFormatTag = WAVE_FORMAT_PCM;
primary_buffer_format.nChannels = 2;
primary_buffer_format.nSamplesPerSec = 44100;
primary_buffer_format.wBitsPerSample = 16;
primary_buffer_format.nBlockAlign = primary_buffer_format.nChannels * primary_buffer_format.wBitsPerSample / 8;
primary_buffer_format.nAvgBytesPerSec = primary_buffer_format.nSamplesPerSec * primary_buffer_format.nBlockAlign;
if (primary_buffer->SetFormat(&primary_buffer_format) != DS_OK) {
std::cout << "Error setting primary buffer format" << std::endl;
primary_buffer->Release();
dsound->Release();
closesocket(socket_client);
WSACleanup();
return 1;
}
// Create secondary buffer
DSBUFFERDESC secondary_buffer_desc;
memset(&secondary_buffer_desc, 0, sizeof(secondary_buffer_desc));
secondary_buffer_desc.dwSize = sizeof(secondary_buffer_desc);
secondary_buffer_desc.dwFlags = 0;
secondary_buffer_desc.dwBufferBytes = file_size;
secondary_buffer_desc.lpwfxFormat = &primary_buffer_format;
IDirectSoundBuffer* secondary_buffer;
if (dsound->CreateSoundBuffer(&secondary_buffer_desc, &secondary_buffer, NULL) != DS_OK) {
std::cout << "Error creating secondary buffer" << std::endl;
primary_buffer->Release();
dsound->Release();
closesocket(socket_client);
WSACleanup();
return 1;
}
DirectSound documentation is confusing me and I can't find why is not working properly
Related
Here's my entire program:
#include <iostream>
#include <windows.h>
int main() {
//? create the serial port file with read and write perms
HANDLE hPort = CreateFileW(L"COM3",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
0,
0);
if (hPort == INVALID_HANDLE_VALUE) {
std::cout << "INVALID_HANDLE_VALUE/6\n";
if (GetLastError() == 2) {
std::cout << "serial port doesn't exist. error code: 2/ERROR_FILE_NOT_FOUND\n";
} else {
std::cout << "error occured with serial port file creation (CreateFileW). error code: " << GetLastError() << std::endl;
}
CloseHandle(hPort);
} else {
std::cout << "serial port created successfully (probably)\n";
}
DCB port_conf;
int err = GetCommState(hPort, &port_conf);
if (err == 0) {
std::cout << "GetCommState failed. error code: " << GetLastError() << "\n";
CloseHandle(hPort);
}
port_conf.BaudRate = 9600;
port_conf.Parity = NOPARITY;
port_conf.ByteSize = 8;
port_conf.StopBits = ONESTOPBIT;
port_conf.DCBlength = sizeof(port_conf);
err = SetCommState(hPort, &port_conf);
COMMTIMEOUTS timeouts_conf;
timeouts_conf.ReadIntervalTimeout = 1;
timeouts_conf.ReadTotalTimeoutConstant = 1;
timeouts_conf.ReadTotalTimeoutMultiplier = 1;
timeouts_conf.WriteTotalTimeoutConstant = 1;
timeouts_conf.WriteTotalTimeoutMultiplier = 1;
err = SetCommTimeouts(hPort, &timeouts_conf);
DWORD buffer_size_read;
char buffer_read[512]{};
int buffer_read_size;
char buffer_read_last[512]{};
while (1){
ReadFile(hPort,
buffer_read,
512,
&buffer_size_read,
0);
std::cout << buffer_read;
// if (buffer_read_last != buffer_read) {
// std::cout << buffer_read;
// }
// buffer_read_size = strlen(buffer_read);
// for (int i = 0; i <= buffer_read_size; i++) {
// buffer_read_last[i] = buffer_read[i];
// }
if (GetKeyState(VK_SPACE) != 0) {
break;
}
}
CloseHandle(hPort);
}
The problem with it is that everything is spit out too fast into cout. I made a miserable attempt at limiting this (it is commented out), but the program just doesn't do anything then. Another attempt was using the timeouts_conf.ReadIntervalTimeout, which Microsoft describes this way:
The maximum time allowed to elapse before the arrival of the next byte on the communications line, in milliseconds. If the interval between the arrival of any two bytes exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.
but it didn't change anything. The serial port is continuously receiving data from a microcontroller in which I will not do the limiting for a pretty specific reason.
I need some sort of reliable way of not spitting everything out to cout at the speed of light. Thanks in advance
I need to close and then reuse the same socket in my app. The first time the socket connects it's able to connect properly, but a second time it's tried to be used, client gets a wsaerror 10054 (existing connection was forcibly closed by the remote host) from the server, and I see that server does not receive the "syn" data from the client. What seems to be wrong here? The client that has connected before is able to connect to a server again, but a server that has received a connection before is unable to accept a new connection as it somehow causes a 10054.
connectionmanager.hpp
#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <iostream>
#include <string>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_PORT 27015
#define DEFAULT_BUFFER_LENGTH 64
class ConnectionManager {
private:
fd_set fdset;
struct timeval client_wait_timeout;
struct timeval server_wait_timeout;
SOCKET sock = INVALID_SOCKET;
// This is where we'll be setting up connection parameters or where we'll be storing the parameters for a connection that's made.
SOCKADDR_IN connection_data;
int connection_data_len = sizeof(connection_data);
char receive_buffer[DEFAULT_BUFFER_LENGTH] = { 0 }; // The object where the recieved data will be placed on.
public:
std::wstring server_ipv4;
bool is_connected = false;
std::string type = "none";
ConnectionManager();
void init(std::string connection_type);
void reset();
bool establish_first_connection();
bool await_first_connection();
std::string receive_data();
std::string send_data(std::string data);
};
connectionmanager.cpp
#include "connection_manager.hpp"
ConnectionManager::ConnectionManager() {
WSADATA wsadata;
int result;
// Initialize Windows Sockets library, version 2.2.
result = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (result != 0)
std::cerr << "WSAStartup failed, error: " << result << "\n";
connection_data.sin_family = AF_INET; // Using IPv4
connection_data.sin_port = htons(DEFAULT_PORT);
}
void ConnectionManager::init(std::string connection_type) {
int result = 0;
if (connection_type == "server") {
connection_data.sin_addr.s_addr = INADDR_ANY; // Bind the socket to all available interfaces - or in other words, accept connections from any IPv4 address. We'll change this after we establish our first connection with the client.
// Create a socket for the server to listen from client for data / send data to client.
sock = socket(connection_data.sin_family, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) {
std::cerr << "Error occured while creating server socket: " << WSAGetLastError() << "\n";
WSACleanup();
}
// Bind the listening socket.
result = bind(sock, (SOCKADDR*)&connection_data, connection_data_len);
if (result == SOCKET_ERROR) {
std::cerr << "Listening socket bind failed with error: " << WSAGetLastError() << "\n";
closesocket(sock);
WSACleanup();
}
std::cout << "Awaiting connection..." << "\n";
if (!await_first_connection())
std::cerr << "Either no one connnected during the 60 second period, or there was a problem with the server. Last WSA error:" << WSAGetLastError() << "\n";
else {
std::cout << "Connected successfully!" << "\n";
is_connected = true;
}
}
else if (connection_type == "client") {
InetPton(connection_data.sin_family, (PCWSTR)(server_ipv4.c_str()), &connection_data.sin_addr.s_addr); // Set the IP address to connect to on the connection_data structure.
// Create a socket for sending data to server.
sock = socket(connection_data.sin_family, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
std::cerr << "Error occured while creating client socket: " << WSAGetLastError() << "\n";
WSACleanup();
}
std::wcout << "Attempting to connect to " << server_ipv4 << "..." << "\n";
if (!establish_first_connection())
std::cerr << "There was a problem connecting the server. Last WSA error: " << WSAGetLastError() << "\n";
else {
std::wcout << "Successfully connected to " << server_ipv4 << "!" << "\n";
is_connected = true;
}
}
// Put the socket in non-blocking mode.
unsigned long mode = 1;
if (ioctlsocket(sock, FIONBIO, (unsigned long*)&mode) == SOCKET_ERROR) {
std::cerr << "Error while putting the socket into non-blocking mode: " << WSAGetLastError() << "\n";
}
}
void ConnectionManager::reset() {
is_connected = false;
closesocket(sock);
}
/*
Functions "establish_first_connection" and "await_first_connection" do something that's quite similar to the three-way handshake method of a TCP connection.
*/
bool ConnectionManager::establish_first_connection() { // This will be used by the client.
// Set up the file descriptor set.
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
int send_result = INT32_MAX;
std::string syn_message = "SYN";
send_result = sendto(sock, syn_message.c_str(), syn_message.length(), 0, (SOCKADDR*)&connection_data, connection_data_len);
if (send_result == SOCKET_ERROR) {
std::cerr << "Error occured while attempting to send SYN to server: " << WSAGetLastError() << "\n";
}
else {
int result = 0;
int receive_result = 0;
// Set up the timeval struct for the timeout.
// We'll wait for 10 seconds for the server to respond, or else we'll call the connection off.
client_wait_timeout.tv_sec = 10; // seconds
client_wait_timeout.tv_usec = 0; // microseconds
// Wait until the timeout or until we receive data.
result = select(sock, &fdset, NULL, NULL, &client_wait_timeout);
if (result == 0)
std::cout << "Timeout." << "\n"; // todo
else if (result == -1)
std::cerr << "Error occured while awaiting first connection data from server. Last WSA error:" << WSAGetLastError() << "\n";
receive_result = recvfrom(sock, receive_buffer, DEFAULT_BUFFER_LENGTH, 0, (SOCKADDR*)&connection_data, &connection_data_len);
if (receive_result > 0) { // If we received any data before the timeout, return true.
std::string client_ack_message = "ACK";
std::cout << receive_buffer << "\n";
sendto(sock, client_ack_message.c_str(), client_ack_message.length(), 0, (SOCKADDR*)&connection_data, connection_data_len);
return true;
}
}
return false;
}
bool ConnectionManager::await_first_connection() { // This will be used by the server.
int result = 0;
int receive_result = 0;
int send_result = 0;
// Set up the file descriptor set.
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
// Set up the timeval struct for the timeout.
// We'll wait for 60 seconds for someone to connect and if someone doesn't connect, we'll cancel the server.
server_wait_timeout.tv_sec = 60; // seconds
server_wait_timeout.tv_usec = 0; // microseconds
// Wait until the timeout or until we receive data.
result = select(sock, &fdset, NULL, NULL, &server_wait_timeout);
if (result == 0) {
std::cout << "Timeout." << "\n";
return false;
}
else if (result == -1)
std::cerr << "Error occured while awaiting first connection data from client. Last WSA error: " << WSAGetLastError() << "\n";
receive_result = recvfrom(sock, receive_buffer, DEFAULT_BUFFER_LENGTH, 0, (SOCKADDR*)&connection_data, &connection_data_len); // We set the first connected client as the only suitable connector from now on here.
if (receive_result > 0) { // If we received any data before the timeout, let the client know that we acknowledge their request and return true.
std::string ack_message = "ACK";
send_result = sendto(sock, ack_message.c_str(), ack_message.length(), 0, (SOCKADDR*)&connection_data, connection_data_len); // Let the client know that we received their message.
if (send_result != SOCKET_ERROR)
return true;
}
return false;
}
std::string ConnectionManager::receive_data() {
ZeroMemory(receive_buffer, DEFAULT_BUFFER_LENGTH); // Clean the receive buffer of any possibly remaining data.
int receive_result = 42;
u_long ioctl_result = 123;
while (true) { // When ioctl with FIONREAD results 0, that means there's no datagram pending in the receive queue. We'll use this to grab only the last received package.
receive_result = recvfrom(sock, receive_buffer, DEFAULT_BUFFER_LENGTH, 0, (SOCKADDR*)&connection_data, &connection_data_len);
ioctlsocket(sock, FIONREAD, &ioctl_result);
if (ioctl_result == 0)
break;
}
// Handle errors.
if (receive_result > 0) {
return std::string(receive_buffer, receive_result); // Using the built-in method of casting char to std::string.
}
else if (receive_result == 0)
return "RECEIVEDNOTHING";
else if (receive_result == SOCKET_ERROR)
switch (WSAGetLastError()) {
case WSAEWOULDBLOCK:
return "WOULDBLOCK";
break;
case WSAECONNRESET:
return "CONNRESET";
break;
case NTE_OP_OK:
break;
default:
std::cerr << "Unhandled error while receiving data: " << WSAGetLastError() << "\n";
}
return "NONE";
}
std::string ConnectionManager::send_data(std::string data) {
int send_result = 666;
send_result = sendto(sock, data.c_str(), data.length(), 0, (SOCKADDR*)&connection_data, connection_data_len);
// Handle errors.
if (send_result == SOCKET_ERROR) {
std::cerr << "Error while sending data: " << WSAGetLastError() << "\n";
return std::string("FAIL");
}
else
return std::string("OK");
}
main.cpp
#include <iostream>
#include <string>
#include "connectionmanager.hpp"
int main() {
ConnectionManager connection_manager;
std::string connection_type;
std::cout << "server or client?" << "\n";
std::cin >> connection_type;
if (connection_type == "client") {
std::wstring ipv4_addr;
std::cout << "ip address?" << "\n";
std::wcin >> ipv4_addr;
connection_manager.server_ipv4 = ipv4_addr;
}
connection_manager.type = connection_type;
connection_manager.init(); // this works fine
connection_manager.reset();
connection_manager.init(); // client returns wsaerror 10054, server receives no data
}
I was able to solve this issue by moving the sin_family and sin_port initialization to ConnectionManager::init() from the constructor and by editing the ConnectionManager::reset() to look like this:
void ConnectionManager::reset() {
puts("reset!");
is_connected = false;
closesocket(sock);
sock = INVALID_SOCKET;
memset(&connection_data, 0, sizeof(connection_data)); // Get rid of the data from the previous connection.
memset(&receive_buffer, 0, sizeof(receive_buffer));
}
I am doing a network abstraction that runs in Linux and Windows.
To create the server socket I do this :
int TCPSocket::create(unsigned int port)
{
_type = SERVER;
char *ip;
int error;
_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (_sock == INVALID_SOCKET)
{
std::cerr <<"Winsock error - Socket creation Failed!\n" << std::endl;
throw std::exception();
}
_sockAddr.sin_family = AF_INET;
_sockAddr.sin_port = htons(port);
hostent* thisHost;
thisHost = gethostbyname("");
ip = inet_ntoa (*(struct in_addr *)*thisHost->h_addr_list);
_sockAddr.sin_addr.s_addr = inet_addr(ip);
error = bind(_sock, (SOCKADDR *) &_sockAddr, sizeof(SOCKADDR));
if (error == SOCKET_ERROR)
{
std::cerr << "bind() failed with error: " << WSAGetLastError() << std::endl;
closesocket(_sock);
WSACleanup();
throw std::exception();
}
error = listen(_sock, 1);
if (error == SOCKET_ERROR)
{
std::cerr << "listen() failed with error: " << WSAGetLastError() << std::endl;
closesocket(_sock);
WSACleanup();
throw std::exception();
}
return _sock;
}
I push this socket in my vector of TCPSocket
error = WSAStartup(MAKEWORD(2,2), &_wsaData);
if (error)
{
std::cerr << "WSAStartup() failed with error:" << error << std::endl;
throw std::exception();
}
TCPSocket *servSock = new TCPSocket();
int fdCreated = servSock->create(_port);
_fdList.push_back(servSock);
Then I use select this way :
fd_set fd_read;
fd_set fd_write;
int fdMax;
int i = 0;
int selectRet;
FD_ZERO(&fd_read);
FD_ZERO(&fd_write);
fdMax = 0;
for (ISocket *tmpSock: _fdList)
{
TCPSocket *socket = reinterpret_cast<TCPSocket *>(tmpSock);
if (socket->getType() != TCPSocket::FREE)
{
FD_SET(socket->getSock(), &fd_read);
FD_SET(socket->getSock(), &fd_write);
fdMax = socket->getSock();
}
i++;
}
if ((selectRet = select(fdMax + 1, &fd_read, &fd_write, NULL, NULL)) == -1)
{
perror("select");
throw std::exception();
}
std::cout << "good" << std::endl;
std::cout << selectRet << std::endl;
if (selectRet > 0)
this->eventAction(fd_read, fd_write);
Problem is, the select() function is blocking (it is normal I know that) but when I connect a client to the server by the way of the windows telnet (telnet localhost port) the select() call still doesn't return anything.
This is working fine on Unix version.
I also noticed that the file descriptor returned by the socket call is very high, it is superior to 250, is it normal ? On Unix it returns always a file descriptor inferior de 5.
I believe that you can also set the s_addr to zero so that it binds the socket to all available addresses or to htonl(0x7f000001) for "127.0.0.1" explicitly. The definition of "localhost" can be surprising.
– D.Shawley
#D.Shawley You were right, i set s_addrto 0 and that worked !
– Dimitri Danilov
it may be a strange request, but, actually, I would like make my call to recv() blocking.
It appears that it should be blocking by default, but for me, it is not, and I can't find any way to make it.
I have a very simple server application, "open socket - bind - wait for connection - receive" on one hand,
and, on the other hand, a simple "open socket - connect - send" client application.
They communicate on LocalHost.
Server :
int clTcpServer::openSocket(void)
{
this->__iLocalSocketId = socket(AF_INET, //stand for IPV4
SOCK_STREAM, //using TCP protocol
0); //no specified / ip protocol
return 0;
}
int clTcpServer::openServer(uint16_t u16Port)
{
this->__strServerInfo.sin_family = AF_INET; // stand for IPV4
this->__strServerInfo.sin_addr.s_addr = INADDR_ANY; // Listen to any address (no filter)
this->__strServerInfo.sin_port = htons(u16Port);
if(bind(this->__iLocalSocketId, (sockaddr *)&this->__strServerInfo, sizeof(this->__strServerInfo)) < 0)
{
std::cout << "TCP server - ERROR - Can't bind socket to port " << std::dec << (int)u16Port << std::endl;
return -1;
}
std::cout << "TCP server - Server opened" << std::endl;
listen(this->__iLocalSocketId, 3);
return 0;
}
int clTcpServer::waitForConnection(void)
{
int iClientIpInfo;
char* pcClientIp;
std::cout << "Waiting for connection ..." << std::endl;
iClientIpInfo = sizeof(struct sockaddr_in);
this->__iDistantSocketId = accept(this->__iLocalSocketId,
(sockaddr *)&this->__strClientInfo,
(socklen_t*)&iClientIpInfo);
if(this->__iDistantSocketId < 0)
{
std::cout << "TCP server - ERROR - Connection refused" << std::endl;
return -1;
}
pcClientIp = inet_ntoa(this->__strClientInfo.sin_addr);
std::cout << "Connection accepted from " << pcClientIp << std::endl;
return 0;
}
int clTcpServer::receiveDataBuffer(void * pvidBuffer, size_t sizeMaxBufferSize)
{
int iRecvSize;
iRecvSize = recv(this->__iDistantSocketId, pvidBuffer, sizeMaxBufferSize, (int)0);
if (iRecvSize < (int)0 )
{
std::cout << "TCP server - ERROR - Recv failed" << std::endl;
return -1;
}
return iSentSize;
}
Client :
int clTcpClient::openSocket(void)
{
/* Create a new socket for client comm. */
this->__iSocketId = socket( AF_INET, //stand for IPV4
SOCK_STREAM, //using TCP protocol
0); //no specified / ip protocol
if (this->__iSocketId == (int)-1)
{
std::cout << "TCP client - ERROR - Can't open Socket" << std::endl;
return -1;
}
return 0;
}
int clTcpClient::connectToServer(std::string stgIpAddress, uint16_t u16Port)
{
/* configure server info according to parameters */
this->__strServerInfo.sin_family = AF_INET; //stand for IPV4
this->__strServerInfo.sin_port = htons(u16Port);
/* Retrieve IP addr*/
this->__strServerInfo.sin_addr.s_addr = inet_addr(stgIpAddress.c_str());
/* Try to connect to the server */
if (connect(this->__iSocketId,
(sockaddr*)&this->__strServerInfo,
sizeof(this->__strServerInfo)) < 0)
{
std::cout << "TCP client - ERROR - Can't connect to " << stgIpAddress << ":" << std::dec << (int)u16Port << std::endl;
return -1;
}
std::cout << "TCP client - Connected" << std::endl;
return 0;
}
int clTcpClient::sendDataBuffer(const void *kpvidData, size_t sizeDataLength)
{
ssize_t sizeSentSize;
/* Send the buffer */
sizeSentSize = send(this->__iSocketId, kpvidData, sizeDataLength, (int)0);
if (sizeSentSize < (ssize_t)0 )
{
std::cout << "TCP client - ERROR - Send failed" << std::endl;
return -1;
}
std::cout << "TCP client - " << (int)sizeSentSize << " byte(s) sent." << std::endl;
return 0;
}
This is working fine, but recv() here is not blocking. If I call it (after having initialized all the stuff, of course), if there is nothing to receive, the function returns 0, as "0 byte received", and that's all.
It means If I want to put this recv function in a loop, CPU is working 100% to receive ... nothing.
What's wrong here ?How can I make it blocking ?
Thank you
I am trying to make RS-232 communication between the PC and the PC MCU PIC. So I started making the PC program first in C++, and it was errorless, and according to the cout I made to output the status it should be working, but I wanted to be sure. So I downloaded Hyperterminal and connected Tx to Rx pin in serial com port, but whenever I try to connect the hyperterminal it gives an error, saying access denied (error 5) when I try to run my C++ program. I don't understand where the problem really is. Here's the full code, if the problem was the code's, just to make sure:
main.c:
#include <windows.h>
#include <winbase.h>
#include <iostream>
PDWORD sent;
char buf;
int main(){
DCB serial;
HANDLE hserial = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
serial.DCBlength = sizeof(DCB);
serial.BaudRate = CBR_9600;
serial.fBinary = true;
serial.fParity = false;
serial.ByteSize = 8;
serial.Parity = NOPARITY;
serial.StopBits = ONESTOPBIT;
char result = BuildCommDCB("baud=9600 parity=N data=8 stop=1", &serial);
if(result != 0){
std::cout << "DCB Structure Successfully Created!" << std::endl;
}else{
std::cout << "DCB Structure Creation Failed!" << std::endl;
}
if(hserial != INVALID_HANDLE_VALUE){
std::cout << "COM Port Handle Successfully Created!" << std::endl;
}else{
std::cout << "COM Port Handle Creation Failed!" << std::endl;
std::cout << GetLastError() << std::endl;
}
char res = WriteFile(hserial, "0xFF", 1, sent, NULL);
if(res != 0){
std::cout << "Writing to COM Port Successfull!" << std::endl;
}else{
std::cout << "Writing to COM Port Failed!" << std::endl;
std::cout << GetLastError() << std::endl;
}
CloseHandle(&hserial);
return 0;
}
Only one program at a time can open a particular COM port. You can do your test if you have two COM ports available.