多线程聊天室程序 基于SDK

哈哈哈哈  终于完成了 ,NND 写了2.

 

虽然完成了,虽然在机器上运行了,虽然能运行得很好,还虽然能发消息和能收消息.(说了怎么多虽然了肯定要有"但是"来衬托了),但是啊,还有很多我不满意的地方

 

第一:全局变量太多,都怪自己太懒,不愿意传参数,看看一般能设置为全局变量的都设置为全局变量了,懒啊!!下次一定改,不改是小狗!

 

第二:程序中没有面向对象的设计风格,虽然定义了几个模块,但是模块之间还是被那些全局变量给联系在一起,整个程序像一团乱麻,剪不断,理还乱,是离愁,恰似一江春水向东流,都说那里去,打住!!

 

第三:写作风格有待提高,这里的风格和很多因素有关 自己的能力,扎实的基础,良好的程序设计习惯,等等........这些都不是一日之功,虽然说不是一日之功,但是要天天注意自己的习惯,就拿那个命名法来说吧,老是忘记,一个字符串老是喜欢写成str  一般的写法是szStr;还有很多东西,比如那个什么指针的分配,在释放指针的空间后老是忘记P=NULL;操作了,.这些基本能力以后写程序的时候慢慢注意点,相信自己很快就能适应.

 

还有几个不足地方现在忘记了,下次想到了再写上来吧

谁要源码和我联系

客户端

//==================================头文件============================================

//#include <windows.h>

#include<Winsock2.h>

#include<stdio.h>

#include <process.h>

#include "resource.h"

//==========================定义消息====================================================

#define WM_RECVDATA WM_USER+100

//===========================库文件=====================================================

#pragma comment(lib, "ws2_32.lib")

#pragma comment(lib, "mswsock.lib")

 

//========================全局变量=====================================================

HWND g_DialogHwnd;    //定义对话框句柄

SOCKET g_ClientSocket; //定义SOCKET对象用来连接服务器的套结字

char szTempBuffer[9999];

sockaddr_in addrSock;//服务器的地址

//SOCKET g_RecvSocket;//用来接收消息的套结字

//=========================全局函数=====================================================

BOOL CALLBACK DialogFun(HWND, UINT,WPARAM, LPARAM);

DWORD InitSocketVersion();//协议协商

BOOL InitSocket();       //创建并绑定socket

BOOL OnSend();           //用来发送消息的

void __cdecl  ReceiveMessage(void*);//线程函数,用来接受消息的用来监听消息的

 

//======================================================================================

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)

{

       MSG msg;

       if(100==DialogBox(hinstance,"mydialog",NULL,(DLGPROC)DialogFun))

       {

              PostQuitMessage(WM_QUIT);

       }

       while (GetMessage(&msg, (HWND) NULL, 0, 0))

       {  

              TranslateMessage(&msg);

              DispatchMessage(&msg);

       }

       //WSACleanup();

       return msg.wParam;

       UNREFERENCED_PARAMETER(lpCmdLine);

      

}

//====================================================================================

BOOL CALLBACK DialogFun(HWND dlghwnd, UINT message,WPARAM wParam, LPARAM lParam)

{

       g_DialogHwnd=dlghwnd;

       switch(message)

       { 

       case WM_PAINT:

              return FALSE;

       case   WM_INITDIALOG :

             

              {  

                     InitSocketVersion();

                     //InitSocket();

                     return FALSE;

              }

       case WM_RECVDATA: //使用接受到消息,并显示于对话框上

              {  

                     char str[9999];

                     GetDlgItemText(g_DialogHwnd,IDC_DISPLAYTEXT,str,9999);

                     sprintf(str,"%s/r/n%s",str,szTempBuffer);

                     SetDlgItemText(g_DialogHwnd,IDC_DISPLAYTEXT,str);

                     SetDlgItemText(g_DialogHwnd,IDC_SENDTEXT,"");

                     SetFocus((HWND)IDC_SENDTEXT);

                     break;

              }

       case WM_COMMAND:

              {

                     switch(LOWORD(wParam))

                     {

                     case IDOK:

                            {

                                   if(MessageBox(g_DialogHwnd,"我想死你了","笨蛋",33)==1)

                                   {

                                          closesocket(g_ClientSocket);

                                          WSACleanup();

                                          EndDialog(g_DialogHwnd,100);//定义100来确定退出对话框

                                   }

                                   break;

                            }

                     case IDC_SEND:

                            {

                                   OnSend();

                                   break;

                            }

                     case IDC_CONNECT:

                            {

                                   //创建新的线程来接受客户端的消息

                                   //InitSocket();

                                   _beginthread(ReceiveMessage,0,(void*)&g_DialogHwnd);

                                   break;

                            }

                            return FALSE;

                     }

                     return FALSE;

              }

              return FALSE;

       }

       return FALSE;

}

 

//==================================================================================

DWORD InitSocketVersion()

{

    WSADATA wsaData;

       return WSAStartup( MAKEWORD( 2, 2 ), &wsaData );

}

//===================================================================================

BOOL InitSocket()

{

       g_ClientSocket=socket(AF_INET,SOCK_STREAM,0);//创建数TCP方式的SOCKET

       if(INVALID_SOCKET==g_ClientSocket)//判断是否创建成功

       {

              MessageBox(g_DialogHwnd,"创建SOCKET失败","错误",MB_OK);

              return FALSE;

       }

       //从对话框上取出端口

       BOOL b_ensure;

       int port;

       port=GetDlgItemInt(g_DialogHwnd,IDC_PORT,&b_ensure,FALSE);

       if(FALSE==b_ensure)

       {

              MessageBox(g_DialogHwnd,"取得服务器端口失败","错误",MB_OK);

              return FALSE;

       }

       //从对话框上取得IP地址

       char HostAdress[20];

       if(0==GetDlgItemText(g_DialogHwnd,IDC_IPADDRESS,HostAdress,sizeof(HostAdress)))

       {

              MessageBox(g_DialogHwnd,"取得服务器IP失败","错误",MB_OK);

              return FALSE;

       }

    //填充地址结构体

       addrSock.sin_family=AF_INET;

       addrSock.sin_port=htons(port);

       addrSock.sin_addr.S_un.S_addr=inet_addr(HostAdress);

      

       if (connect(g_ClientSocket, (SOCKADDR*) &addrSock, sizeof(sockaddr_in) ) == SOCKET_ERROR)

       {

              MessageBox(g_DialogHwnd,"连接不了服务器","笨蛋",MB_ICONWARNING);

              WSACleanup();

              return 1;

       }

       //else

       //MessageBox(g_DialogHwnd,"连接成功","恭喜你是成猪了",MB_ICONWARNING);

      

       return TRUE;

}

 

BOOL OnSend()

{

       InitSocket();

       char szStrSend[1023];//消息

       char name[12];//名字

       char szSend[1023];

       GetDlgItemText(g_DialogHwnd,IDC_SENDTEXT,szStrSend,1023);

    GetDlgItemText(g_DialogHwnd,IDC_NAME,name,8);

       strcpy(szSend,szStrSend);

       sprintf(szStrSend,"%s%s",name,szSend);

       send(g_ClientSocket,szStrSend,sizeof(szStrSend)+1,0);

       return TRUE;

}

//===================================================================================

void __cdecl ReceiveMessage(void* lpParameter)

{

   while(1)

       {

              char szRecvBuffer[1024];

              if(SOCKET_ERROR==recv(g_ClientSocket,szRecvBuffer,1024,0))break;

              sprintf(szTempBuffer,"%s",szRecvBuffer);

              PostMessage(g_DialogHwnd,WM_RECVDATA,0,0);

       }

}

 

 

 

 

服务器端

//==================================头文件============================================

//#include <windows.h>

#include<Winsock2.h>

#include<stdio.h>

#include <process.h>

#include "resource.h"

//==========================定义消息====================================================

#define WM_RECVDATA WM_USER+100

//===========================库文件=====================================================

#pragma comment(lib, "ws2_32.lib")

#pragma comment(lib, "mswsock.lib")

//=========================全局变量=====================================================

char g_szIpAdress[20];//定义IP地址 字符串型的

SOCKET g_Socket;     //定义SOCKET对象

SOCKET g_ClientSocket;//定义接受到的客户端的套结字

HWND g_DialogHwnd;    //定义对话框句柄

char szTempBuffer[9999];

//=========================全局函数=====================================================

BOOL CALLBACK DialogFun(HWND, UINT,WPARAM, LPARAM);

void __cdecl  ReceiveMessage(void*);//线程函数,用来接受消息的用来监听消息的 并显示消息与对话框上,TNND这里要用到多线程处理 麻烦

BOOL GetLocalIP();//取得本主机IP

BOOL SetDlgIpAndPort();//设置为对话框IP

DWORD InitSocketVersion();//协议协商

BOOL InitSocket();   //创建并绑定socket

BOOL OnSend();       //用来发送消息的

//======================================================================================

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)

{

       MSG msg;

       if(100==DialogBox(hinstance,"mydialog",NULL,(DLGPROC)DialogFun))

       {

              PostQuitMessage(WM_QUIT);

       }

       while (GetMessage(&msg, (HWND) NULL, 0, 0))

       {  

              TranslateMessage(&msg);

              DispatchMessage(&msg);

       }

       //WSACleanup();

       return msg.wParam;

       UNREFERENCED_PARAMETER(lpCmdLine);

      

}

//========================================================================================

BOOL CALLBACK DialogFun(HWND dlghwnd, UINT message,WPARAM wParam, LPARAM lParam)

{

       switch(message)

       { 

       case WM_PAINT:

              return FALSE;

       case   WM_INITDIALOG :

             

              {  

                 g_DialogHwnd=dlghwnd;

                     InitSocketVersion();

                     GetLocalIP();

                     SetDlgIpAndPort();

                     InitSocket();

                     listen(g_Socket,5);

                     return FALSE;

              }

       case WM_RECVDATA: //使用接受到消息,并显示于对话框上

              {  

                     char szStr[9999];

                     char szTemp[9999];

                     GetDlgItemText(g_DialogHwnd,IDC_DISPLAYTEXT,szStr,9999);

                     wsprintf(szTemp,"%s/r/n%s",szStr,szTempBuffer);

                     SetDlgItemText(g_DialogHwnd,IDC_DISPLAYTEXT,szTemp);

                     SetDlgItemText(g_DialogHwnd,IDC_SENDTEXT,"");

                     SetFocus((HWND)IDC_SENDTEXT);

              break;

              }

             

       case WM_COMMAND:

              {

                     switch(LOWORD(wParam))

                     {

                     case IDOK:

                            {

                                   if(MessageBox(g_DialogHwnd,"我想死你了","笨蛋",33)==1)

                                   {

                                          closesocket(g_Socket);

                                          closesocket(g_ClientSocket);

                                          WSACleanup();

                                          EndDialog(g_DialogHwnd,100);//定义100来确定退出对话框

                                          //PostQuitMessage(0); //也可以使用这个消息来退出循坏

                                   }

                                   return TRUE;

                            }

                     case IDC_SET_PORTANDIP:

                            {

                                  

                                   //创建新的线程来接受客户端的消息

                                   _beginthread(ReceiveMessage,0,(void*)&g_DialogHwnd);

                                   break;

                            }

                     case IDC_SEND:

                            {

                                   OnSend();

                                   break;

                            }

                     }

                    

                     return FALSE;

              }

              return FALSE;

       }

       return FALSE;

}

//=======================================================================================

BOOL GetLocalIP()

{  

       char NameBuffer[250];//定义存放主机名字的缓冲区

       if(SOCKET_ERROR==gethostname(NameBuffer,sizeof(NameBuffer)))

       {

              return FALSE;

       }

    hostent* IpAdress=gethostbyname(NameBuffer);//IpAdress存放网络字节的IP地址

       if(NULL==inet_ntoa (*(struct in_addr *)*IpAdress->h_addr_list))

       {

              return FALSE;

       }

       //g_szIpAdress来保存IP的地址

       strcpy (g_szIpAdress,inet_ntoa (*(struct in_addr *)*IpAdress->h_addr_list));

       return TRUE;

}

//=====================================================================================

BOOL SetDlgIpAndPort()

{

    SetDlgItemText(g_DialogHwnd,IDC_IPADDRESS,g_szIpAdress);

       SetDlgItemInt(g_DialogHwnd,IDC_PORT,5200,FALSE);

       return 0;

}

 

DWORD InitSocketVersion()

{

    WSADATA wsaData;

       return WSAStartup( MAKEWORD( 2, 2 ), &wsaData );

}

//==========================================================================================

BOOL InitSocket()

{

       g_Socket=socket(AF_INET,SOCK_STREAM,0);//创建数TCP方式的SOCKET

       if(INVALID_SOCKET==g_Socket)//判断是否创建成功

       {

              MessageBox(g_DialogHwnd,"创建SOCKET失败","错误",MB_OK);

              return FALSE;

       }

       //从对话框上取出端口

       BOOL b_ensure;

       int port;

       port=GetDlgItemInt(g_DialogHwnd,IDC_PORT,&b_ensure,FALSE);

       if(FALSE==b_ensure)

       {

              MessageBox(g_DialogHwnd,"取得端口失败","错误",MB_OK);

              return FALSE;

       }

       //从对话框上取得IP地址

       char HostAdress[20];

       if(0==GetDlgItemText(g_DialogHwnd,IDC_IPADDRESS,HostAdress,sizeof(HostAdress)))

       {

              MessageBox(g_DialogHwnd,"取得IP失败","错误",MB_OK);

              return FALSE;

       }

    //填充地址结构体

       sockaddr_in addrSock;

       addrSock.sin_family=AF_INET;

       addrSock.sin_port=htons(port);

       addrSock.sin_addr.S_un.S_addr=inet_addr(HostAdress);

       //bind

       if(SOCKET_ERROR==bind(g_Socket,(SOCKADDR*)&addrSock,sizeof(addrSock)))

       {

              closesocket(g_Socket);

              MessageBox(g_DialogHwnd,"BIND失败","错误",MB_OK);

              return FALSE;

       }

       return TRUE;

}

//=================================================================================

void __cdecl ReceiveMessage(void* lpParameter)

{

      

       sockaddr_in m_Client;

       int ClientLen=sizeof(sockaddr_in);

       //下面是开始的时候的错误,TNND 把握居然把accept放在循环外面了 大错了

       //m_ClientSocket=accept(g_Socket,(SOCKADDR*)&m_Client,&ClientLen);

       //char szRecvBuffer[1024];

       while(1)

       {

              g_ClientSocket=accept(g_Socket,(SOCKADDR*)&m_Client,&ClientLen);

              char szRecvBuffer[1024];

              if(SOCKET_ERROR==recv(g_ClientSocket,szRecvBuffer,1024,0))break;

              sprintf(szTempBuffer,"%s",szRecvBuffer);

              PostMessage(g_DialogHwnd,WM_RECVDATA,0,0);

       }

 

}

//=================================================================================

BOOL OnSend()

{

       char szStrSend[1023];

       char szName[8];//名字

       char szTempSend[1023];

       GetDlgItemText(g_DialogHwnd,IDC_SENDTEXT,szStrSend,1023);

       GetDlgItemText(g_DialogHwnd,IDC_NAME,szName,8);

       sprintf(szTempSend,"%s:%s",szName,szStrSend);

    send(g_ClientSocket,szTempSend,1024,0);

       return TRUE;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值