server端
SOCKET clientsocket;
HANDLE handleThread;
DWORD WINAPI WinPorc(LPVOID lparam);
void CSocketDlg::OnButton2() //1.创建主Socket
{
mysocket = socket(AF_INET,SOCK_STREAM,0);
if (mysocket == INVALID_SOCKET)
{
MessageBox(L"MySocket failed");
}
else
{
MessageBox(L"MySocket Success");
}
}
void CSocketDlg::OnButtonBind() //2.给主Socket绑定端口信息
{
sockaddr_in serversocketinfo;
serversocketinfo.sin_family = AF_INET;
serversocketinfo.sin_port = htons(PORT1);
serversocketinfo.sin_addr.s_addr = INADDR_ANY;
memset(serversocketinfo.sin_zero,0,8);
if(bind(mysocket,(sockaddr*)&serversocketinfo,sizeof(serversocketinfo))==0) //强转的参数要加上地址符号&
{
MessageBox(L"Bind success");
}
else
{
MessageBox(L"Bind failed");
}
}
void CSocketDlg::OnButtonListen() //3.用主Socket开始监听客户端
{
if(listen(mysocket,10)==0)
{
MessageBox(L"Listen Success");
}
else
{
MessageBox(L"Listen failed");
}
}
void CSocketDlg::OnButtonAccept() //4.用ClientSocket去等待接收客户端发来的信息
{
sockaddr_in clientsocketinfo;
int size;
size = sizeof(clientsocketinfo);
clientsocket = accept(mysocket,(sockaddr*)&clientsocketinfo,&size);//阻塞函数
if (clientsocket == INVALID_SOCKET)
{
MessageBox(L"ClientSocket failed");
}
else
{
MessageBox(L"ClientSocket Success");
}
handleThread = CreateThread(NULL,0,WinPorc,NULL,NULL,NULL);
}
DWORD WINAPI WinPorc(LPVOID lparam)
{
char buf[1024];
CSocketDlg* p = (CSocketDlg*)AfxGetApp()->GetMainWnd();
while (1)
{
memset(buf,0,1024);
recv(clientsocket,buf,1024,0);//阻塞函数
p->m_edit_show += buf;
AfxGetApp()->GetMainWnd()->SetDlgItemText(IDC_EDIT1,p->m_edit_show);
}
return 0;
}
client端
void CClientSocketDlg::OnButtonCreate()
{
mysocket = socket(AF_INET,SOCK_STREAM,0);
if (mysocket == INVALID_SOCKET)
{
MessageBox(L"Create failed");
}
else
{
MessageBox(L"Create Success");
}
struct hostent* host;
host = gethostbyname("127.0.0.1");
sockaddr_in clientsocketinfo;
clientsocketinfo.sin_addr = *(in_addr*)host->h_addr;
clientsocketinfo.sin_port = htons(PORT1);
clientsocketinfo.sin_family = AF_INET;
memset(clientsocketinfo.sin_zero,0,8);
if(connect(mysocket,(sockaddr*)&clientsocketinfo,sizeof(clientsocketinfo))==0)
{
MessageBox(L"Connect Success");
}
}
void CClientSocketDlg::OnButtonSend()
{
UpdateData(TRUE);
char buf[1024];
wcstombs(buf,m_edit_val,sizeof(buf));
send(mysocket,buf,1024,0);
}