< 2개의 콘솔에서 "Hello World" 메시지를 주고 받기 > - C++ 작성
/* 서버 콘솔 */
#include<stdio.h>
#include<windows.h>
int main(void)
{
char szPort[15]; //포트명을 저장할 변수
wsprintf(szPort, "COM%d", 2); //2번 포트로 통신
//Comm device를 File Open과 같은 방법으로 연결
HANDLE m_hComm=NULL;
m_hComm=CreateFile(szPort,
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(m_hComm==INVALID_HANDLE_VALUE)
{
printf("(!)Failed to create a Comm Device file.");
return FALSE;
}
DCB dcb;
dcb.DCBlength=sizeof(DCB);
GetCommState(m_hComm, &dcb); //DCB초기값
dcb.BaudRate=9600; //전송속도
dcb.ByteSize=8; //테이터비트 4-8
dcb.Parity=0; //Parity 0-4=no, odd, even, mark, space
dcb.StopBits=0; //Stopbit 0,1,1=1,1.5,2
SetCommState(m_hComm, &dcb); //DCB변경
OVERLAPPED osWrite;
osWrite.Offset=0;
osWrite.OffsetHigh=0;
osWrite.hEvent=CreateEvent(NULL, TRUE, FALSE, NULL);
OVERLAPPED osRead;
osRead.Offset=0;
osRead.OffsetHigh=0;
osRead.hEvent=CreateEvent(NULL, TRUE, FALSE, NULL);
char buf[100]="Hello world\r\n";
while(1)
{
WriteFile(m_hComm, buf, sizeof(buf), NULL, &osWrite);
printf("send1:%s", buf);
memset(buf, '\0', sizeof(buf));
ReadFile(m_hComm, buf, sizeof(buf), NULL, &osRead);
printf("recv1:%s", buf);
Sleep(1000);
}
CloseHandle(m_hComm);
return 0;
}
=================================================================================================
/* 클라이언트 콘솔 */
#include<stdio.h>
#include<windows.h>
int main(void)
{
char szPort[15]; //포트명을 저장할 변수
wsprintf(szPort, "COM%d", 5); //2번 포트로 통신
//Comm device를 File Open과 같은 방법으로 연결
HANDLE m_hComm=NULL;
m_hComm=CreateFile(szPort,
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(m_hComm==INVALID_HANDLE_VALUE)
{
printf("(!)Failed to create a Comm Device file.");
return FALSE;
}
DCB dcb;
dcb.DCBlength=sizeof(DCB);
GetCommState(m_hComm, &dcb); //DCB초기값
dcb.BaudRate=9600; //전송속도
dcb.ByteSize=8; //테이터비트 4-8
dcb.Parity=0; //Parity 0-4=no, odd, even, mark, space
dcb.StopBits=0; //Stopbit 0,1,1=1,1.5,2
SetCommState(m_hComm, &dcb);//DCB변경
OVERLAPPED osWrite;
osWrite.Offset=0;
osWrite.OffsetHigh=0;
osWrite.hEvent=CreateEvent(NULL, TRUE, FALSE, NULL);
OVERLAPPED osRead;
osRead.Offset=0;
osRead.OffsetHigh=0;
osRead.hEvent=CreateEvent(NULL, TRUE, FALSE, NULL);
char buf[100];
while(1)
{
memset(buf, '\0', sizeof(buf));
ReadFile(m_hComm, buf, sizeof(buf), NULL, &osRead);
printf("recv2:%s", buf);
WriteFile(m_hComm, buf, sizeof(buf), NULL, &osWrite);
printf("send2:%s", buf);
Sleep(1000);
}
CloseHandle(m_hComm);
return 0;
}
'IT_etc > dk-128 (ATmega128)' 카테고리의 다른 글
[스크랩] 8-2. avr 직렬 양방향 통신 (0) | 2009.08.25 |
---|---|
[스크랩] 8-1. avr 직렬 단방향 통신 (0) | 2009.08.25 |
[스크랩] 7-1. 윈도우 기반 직렬 단방향 통신 (0) | 2009.08.25 |
[스크랩] 6. 외부 EEPROM (0) | 2009.08.25 |
[dk-128] 내부 EEPROM 사용하기 (타이머 카운터 사용) (0) | 2009.07.06 |