1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| CString AddText(CEdit *Edit, const char *Text)
{
CString csTemp, csAdded(Text);
Edit->GetWindowText(csTemp);
csTemp += csAdded;
return csTemp;
}
void CConnectorDlg::OnConnect()
{
EGetDialog = (CEdit *)GetDlgItem(IDC_EDIALOG);
EGetDialog->SetWindowText("Connecting...");
CEdit *EGetHost = (CEdit *)GetDlgItem(IDC_EHOST);
CEdit *EGetPort = (CEdit *)GetDlgItem(IDC_EPORT);
try
{
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
throw "cannot initiate use of ws2_32.dll !";
return;
}
CString csHost, csPort;
char Host[128], Port[10];
EGetHost->GetWindowText(csHost);
EGetPort->GetWindowText(csPort);
strcpy(Host, csHost.GetBuffer(0));
strcpy(Port, csPort.GetBuffer(0));
if(isalpha(Host[0]))
{
struct hostent *Resolv;
if((Resolv = gethostbyname(Host)) != 0)
{
memcpy(&(SockAddr.sin_addr), Resolv->h_addr, Resolv->h_length);
SockAddr.sin_family = AF_INET/*Resolv->h_addrtype*/;
}
else throw("cannot resolving host !");
}
if((Sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
throw "cannot create socket !";
SockAddr.sin_port = htons(atoi(Port));
if(connect(Sock, (struct sockaddr*)&SockAddr, sizeof(SockAddr)) == -1)
throw "failed to connect !";
EGetDialog->SetWindowText(AddText(EGetDialog, "OK"));
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadRecv, 0, 0, 0);
}
catch(const char *ErrorMsg)
{
char Error[128];
sprintf(Error, " error (%s)", ErrorMsg);
EGetDialog->SetWindowText(AddText(EGetDialog, Error));
return;
}
catch(...)
{
EGetDialog->SetWindowText(AddText(EGetDialog, "error (unknow)"));
return;
}
}
void CConnectorDlg::OnDisconnect()
{
EGetDialog->SetWindowText("");
closesocket(Sock);
}
void CConnectorDlg::OnSend()
{
CString csMessage;
char Message_Send[256];
CEdit *EGetDialog = (CEdit *)GetDlgItem(IDC_EDIALOG);
CEdit *EGetMsg = (CEdit *)GetDlgItem(IDC_EREQUEST);
EGetMsg->GetWindowText(csMessage);
memset(Message_Send, 0, sizeof(Message_Send));
strcpy(Message_Send, csMessage.GetBuffer(0));
if(send(Sock, Message_Send, strlen(Message_Send), 0) == -1)
{
EGetDialog->SetWindowText("You're disconnected !");
return;
}
}
void ThreadRecv()
{
char Message_Recv[512];
fd_set SockRecv;
FD_ZERO(&SockRecv);
FD_SET(Sock, &SockRecv);
select(Sock + 1,&SockRecv, 0, 0, 0);
while(1)
{
if(FD_ISSET(Sock, &SockRecv))
{
memset(Message_Recv, 0, sizeof(Message_Recv));
recv(Sock, Message_Recv, sizeof(Message_Recv), 0);
CString csMessage(Message_Recv);
EGetDialog->SetWindowText(csMessage);
}
}
}
void CConnectorDlg::OnCancel()
{
closesocket(Sock);
WSACleanup();
CDialog::OnCancel();
} |
Partager