這是怎麼回事,希望你沒事! 嗯,問題是我正在做一個聊天客戶端/服務器應用程序,但做了一些與服務器的測試,我發現我有一個問題發送消息。我使用的是結構,插座和DWORD WINAPI線程... 所以在結構中的代碼是:結構和線程DWORD WINAPI
DWORD WINAPI threadSendMessages(LPVOID vpParam); //THREAD
typedef struct messagesServerChat{ //STRUCT
const char *messageServEnv;
}MESSAGE, *SMESSAGES;
然後在主方法我稱之爲結構使用爲const char messageServEnv,一個HeapAlloc到給一些內存到是要送我用來
char mServer[1024] = ""; //variable to pre-store the message
SMESSAGES messages; //call the struct
messages = (SMESSAGES) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MESSAGE));
存儲消息在main方法的消息和char變量線程,我要求用戶插入他要發送消息和我使用結構來存儲消息並將其作爲參數發送給線程:
cout<<"Dear user, please insert your message: ";
setbuf(stdin, NULL);
fgets(mServer, 1024, stdin);
messages->messageServEnv = mServer;
DWORD hSend; //send the parameters to the thread function
HANDLE sendThread = CreateThread(0, 0, threadSendMessages, mServer, 0, &hSend);
終於線程代碼功能
DWORD WINAPI threadSendMessages(LPVOID lpParam){
SMESSAGES messages;
messages = (SMESSAGES)lpParam;
int mesa;
mesa = send(sConnect, (char *)messages->messageServEnv, sizeof messages->messageServEnv, 0);
//sConnect is the socket
//messages = to use the struct, and messageServEnv is the struct data that should contain the message
return 0;
}
- 編輯 - 我用雷米的解決方案解決了很多問題,但也許我失去了一些東西...在Thread threadSendMessages(SMESSAGES lpMessage)
char *ptr = messages->messageServEnv;
int len = strlen(messages->messageServEnv);
我得到和錯誤,指出消息的undifined,然後,我改成:
SMESSAGES messages;
char *ptr = messages->messageServEnv;
int len = strlen(messages->messageServEnv);
現在我可以用消息和結構值messageServEnv但如果我開始調試Visual Studio和我嘗試發送一個消息,我得到說消息沒有被初始化使用了錯誤的話,我改變部分到
SMESSAGES messages = new MESSAGE;
,現在我可以將消息發送到客戶端,但只有字符和垃圾代碼
關於編輯,請參閱我的更新答案。 – 2012-04-19 08:39:36