Ⅰ windows下的C語言socket編程沒有相關socket的頭文件怎麼辦
//服務端代碼
#include<winsock2.h>
#include<stdio.h>
#pragma comment(lib,"ws2_32.lib")//這句關鍵;
void main(){
WORD wV;
WSADATA ws;
int er;
wV=MAKEWORD(1,1);
er=WSAStartup(wV,&ws);
if(er!=0){
return;
}
if(LOBYTE(ws.wVersion)!=1||HIBYTE(ws.wVersion)!=1){
WSACleanup();
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
char sendBuf[100];
sprintf(sendBuf,"welcome %s to wozhe",inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[100];
recv(sockConn,recvBuf,100,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}
//客戶端
#include<winsock2.h>
#include<stdio.h>
#pragma comment(lib,"ws2_32.lib")
void main(){
WORD wV;
WSADATA ws;
int er;
wV=MAKEWORD(1,1);
er=WSAStartup(wV,&ws);
if(er!=0){
return;
}
if(LOBYTE(ws.wVersion)!=1||HIBYTE(ws.wVersion)!=1){
WSACleanup();
return;
}
SOCKET sockC=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrS;
addrS.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrS.sin_family=AF_INET;
addrS.sin_port=htons(6000);
connect(sockC,(SOCKADDR*)&addrS,sizeof(SOCKADDR));
char recvB[100];
recv(sockC,recvB,100,0);
printf("%s\n",recvB);
send(sockC,"this is list",strlen("this is list")+1,0);
closesocket(sockC);
WSACleanup();
}
Ⅱ 求VC++中的頭文件Afxcsock.h
直接給你吧,保存為Afxsock.h 不是Afxcsock.h 路徑是 在VC98\MFC\INCLUDE
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1992-1998 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes proct.
#ifndef __AFXSOCK_H__
#define __AFXSOCK_H__
#ifdef _AFX_NO_SOCKET_SUPPORT
#error Windows Sockets classes not supported in this library variant.
#endif
#ifndef __AFXWIN_H__
#include <afxwin.h>
#endif
#ifndef _WINSOCKAPI_
#include <winsock.h>
#endif
#ifdef _AFX_MINREBUILD
#pragma component(minrebuild, off)
#endif
#ifndef _AFX_FULLTYPEINFO
#pragma component(mintypeinfo, on)
#endif
#ifndef _AFX_NOFORCE_LIBS
/////////////////////////////////////////////////////////////////////////////
// Win32 libraries
#ifdef _AFXDLL
#if defined(_DEBUG) && !defined(_AFX_MONOLITHIC)
#ifndef _UNICODE
#pragma comment(lib, "mfcn42d.lib")
#else
#pragma comment(lib, "mfcn42ud.lib")
#endif
#endif
#endif
#pragma comment(lib, "wsock32.lib")
#endif //!_AFX_NOFORCE_LIBS
/////////////////////////////////////////////////////////////////////////////
#ifdef _AFX_PACKING
#pragma pack(push, _AFX_PACKING)
#endif
/////////////////////////////////////////////////////////////////////////////
// AFXSOCK - MFC support for Windows Sockets
// Classes declared in this file
// CObject
class CAsyncSocket; // Async Socket implementation and
// base class for Synchronous Socket
class CSocket; // Synchronous Socket
// CFile
class CSocketFile; // Used with CSocket and CArchive for
// streaming objects on sockets.
/////////////////////////////////////////////////////////////////////////////
// AFXDLL support
#undef AFX_DATA
#define AFX_DATA AFX_NET_DATA
/////////////////////////////////////////////////////////////////////////////
// CSocketWnd -- internal use only
// Implementation for sockets notification callbacks.
// Future versions of MFC may or may not include this exact class.
class CSocketWnd : public CWnd
{
// Construction
public:
CSocketWnd();
protected:
//{{AFX_MSG(CSocketWnd)
LRESULT OnSocketNotify(WPARAM wParam, LPARAM lParam);
LRESULT OnSocketDead(WPARAM wParam, LPARAM lParam);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
// CAsyncSocket
class CAsyncSocket : public CObject
{
DECLARE_DYNAMIC(CAsyncSocket);
private:
CAsyncSocket(const CAsyncSocket& rSrc); // no implementation
void operator=(const CAsyncSocket& rSrc); // no implementation
// Construction
public:
CAsyncSocket();
BOOL Create(UINT nSocketPort = 0, int nSocketType=SOCK_STREAM,
long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,
LPCTSTR lpszSocketAddress = NULL);
// Attributes
public:
SOCKET m_hSocket;
operator SOCKET() const;
BOOL Attach(SOCKET hSocket, long lEvent =
FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE);
SOCKET Detach();
BOOL GetPeerName(CString& rPeerAddress, UINT& rPeerPort);
BOOL GetPeerName(SOCKADDR* lpSockAddr, int* lpSockAddrLen);
BOOL GetSockName(CString& rSocketAddress, UINT& rSocketPort);
BOOL GetSockName(SOCKADDR* lpSockAddr, int* lpSockAddrLen);
BOOL SetSockOpt(int nOptionName, const void* lpOptionValue,
int nOptionLen, int nLevel = SOL_SOCKET);
BOOL GetSockOpt(int nOptionName, void* lpOptionValue,
int* lpOptionLen, int nLevel = SOL_SOCKET);
static CAsyncSocket* PASCAL FromHandle(SOCKET hSocket);
static int PASCAL GetLastError();
// Operations
public:
virtual BOOL Accept(CAsyncSocket& rConnectedSocket,
SOCKADDR* lpSockAddr = NULL, int* lpSockAddrLen = NULL);
BOOL Bind(UINT nSocketPort, LPCTSTR lpszSocketAddress = NULL);
BOOL Bind (const SOCKADDR* lpSockAddr, int nSockAddrLen);
virtual void Close();
BOOL Connect(LPCTSTR lpszHostAddress, UINT nHostPort);
BOOL Connect(const SOCKADDR* lpSockAddr, int nSockAddrLen);
BOOL IOCtl(long lCommand, DWORD* lpArgument);
BOOL Listen(int nConnectionBacklog=5);
virtual int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
int ReceiveFrom(void* lpBuf, int nBufLen,
CString& rSocketAddress, UINT& rSocketPort, int nFlags = 0);
int ReceiveFrom(void* lpBuf, int nBufLen,
SOCKADDR* lpSockAddr, int* lpSockAddrLen, int nFlags = 0);
enum { receives = 0, sends = 1, both = 2 };
BOOL ShutDown(int nHow = sends);
virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
int SendTo(const void* lpBuf, int nBufLen,
UINT nHostPort, LPCTSTR lpszHostAddress = NULL, int nFlags = 0);
int SendTo(const void* lpBuf, int nBufLen,
const SOCKADDR* lpSockAddr, int nSockAddrLen, int nFlags = 0);
BOOL AsyncSelect(long lEvent =
FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE);
// Overridable callbacks
protected:
virtual void OnReceive(int nErrorCode);
virtual void OnSend(int nErrorCode);
virtual void OnOutOfBandData(int nErrorCode);
virtual void OnAccept(int nErrorCode);
virtual void OnConnect(int nErrorCode);
virtual void OnClose(int nErrorCode);
// Implementation
public:
virtual ~CAsyncSocket();
static CAsyncSocket* PASCAL LookupHandle(SOCKET hSocket, BOOL bDead = FALSE);
static void PASCAL AttachHandle(SOCKET hSocket, CAsyncSocket* pSocket, BOOL bDead = FALSE);
static void PASCAL DetachHandle(SOCKET hSocket, BOOL bDead = FALSE);
static void PASCAL KillSocket(SOCKET hSocket, CAsyncSocket* pSocket);
static void PASCAL DoCallBack(WPARAM wParam, LPARAM lParam);
BOOL Socket(int nSocketType=SOCK_STREAM, long lEvent =
FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,
int nProtocolType = 0, int nAddressFormat = PF_INET);
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
friend class CSocketWnd;
virtual BOOL ConnectHelper(const SOCKADDR* lpSockAddr, int nSockAddrLen);
virtual int ReceiveFromHelper(void* lpBuf, int nBufLen,
SOCKADDR* lpSockAddr, int* lpSockAddrLen, int nFlags);
virtual int SendToHelper(const void* lpBuf, int nBufLen,
const SOCKADDR* lpSockAddr, int nSockAddrLen, int nFlags);
};
/////////////////////////////////////////////////////////////////////////////
// CSocket
class CSocket : public CAsyncSocket
{
DECLARE_DYNAMIC(CSocket);
private:
CSocket(const CSocket& rSrc); // no implementation
void operator=(const CSocket& rSrc); // no implementation
// Construction
public:
CSocket();
BOOL Create(UINT nSocketPort = 0, int nSocketType=SOCK_STREAM,
LPCTSTR lpszSocketAddress = NULL);
// Attributes
public:
BOOL IsBlocking();
static CSocket* PASCAL FromHandle(SOCKET hSocket);
BOOL Attach(SOCKET hSocket);
// Operations
public:
void CancelBlockingCall();
// Overridable callbacks
protected:
virtual BOOL OnMessagePending();
// Implementation
public:
int m_nTimeOut;
virtual ~CSocket();
static int PASCAL ProcessAuxQueue();
virtual BOOL Accept(CAsyncSocket& rConnectedSocket,
SOCKADDR* lpSockAddr = NULL, int* lpSockAddrLen = NULL);
virtual void Close();
virtual int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
int SendChunk(const void* lpBuf, int nBufLen, int nFlags);
protected:
friend class CSocketWnd;
BOOL* m_pbBlocking;
int m_nConnectError;
virtual BOOL ConnectHelper(const SOCKADDR* lpSockAddr, int nSockAddrLen);
virtual int ReceiveFromHelper(void* lpBuf, int nBufLen,
SOCKADDR* lpSockAddr, int* lpSockAddrLen, int nFlags);
virtual int SendToHelper(const void* lpBuf, int nBufLen,
const SOCKADDR* lpSockAddr, int nSockAddrLen, int nFlags);
static void PASCAL AuxQueueAdd(UINT message, WPARAM wParam, LPARAM lParam);
virtual BOOL PumpMessages(UINT uStopFlag);
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
};
/////////////////////////////////////////////////////////////////////////////
// CSocketFile
class CSocketFile : public CFile
{
DECLARE_DYNAMIC(CSocketFile)
public:
//Constructors
CSocketFile(CSocket* pSocket, BOOL bArchiveCompatible = TRUE);
// Implementation
public:
CSocket* m_pSocket;
BOOL m_bArchiveCompatible;
virtual ~CSocketFile();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
virtual UINT Read(void* lpBuf, UINT nCount);
virtual void Write(const void* lpBuf, UINT nCount);
virtual void Close();
// Unsupported APIs
virtual BOOL Open(LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError = NULL);
virtual CFile* Duplicate() const;
virtual DWORD GetPosition() const;
virtual LONG Seek(LONG lOff, UINT nFrom);
virtual void SetLength(DWORD dwNewLen);
virtual DWORD GetLength() const;
virtual void LockRange(DWORD dwPos, DWORD dwCount);
virtual void UnlockRange(DWORD dwPos, DWORD dwCount);
virtual void Flush();
virtual void Abort();
};
/////////////////////////////////////////////////////////////////////////////
// Global functions
BOOL AFXAPI AfxSocketInit(WSADATA* lpwsaData = NULL);
void AFXAPI AfxSocketTerm();
/////////////////////////////////////////////////////////////////////////////
// Inline function declarations
#ifdef _AFX_PACKING
#pragma pack(pop)
#endif
#ifdef _AFX_ENABLE_INLINES
#define _AFXSOCK_INLINE AFX_INLINE
#include <afxsock.inl>
#undef _AFXSOCK_INLINE
#endif
#undef AFX_DATA
#define AFX_DATA
#ifdef _AFX_MINREBUILD
#pragma component(minrebuild, on)
#endif
#ifndef _AFX_FULLTYPEINFO
#pragma component(mintypeinfo, off)
#endif
#endif // __AFXSOCK_H__
/////////////////////////////////////////////////////////////////////////////
本質區別是這樣的,linux下用的是伯克利,windows底下用的WinSocket.
兩者其實是大同小異的,不同的地方在以下幾點:
1 頭文件不同,在linux下用到的關鍵頭文件<sys/socket.h>
windows下用到的是 <Winsock2.h>
2 socket的初始化不一樣,在windows下要有一個WSAStartup,而linux 下沒有。
3 具體的細節不一樣,linux下的c和windows下的c的一些語法有些出入,你自己找找。
下面我把windows下的socket通訊的最基本的結構給你,你對照著修改就可以了,一下的程序我調試了一下,編譯過了。
客戶端
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
char recvBuf[100];
recv(sockClient,recvBuf,100,0);
printf("%s\n",recvBuf);
send(sockClient,"This is lisi",strlen("This is lisi")+1,0);
closesocket(sockClient);
WSACleanup();
}
伺服器端
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
char sendBuf[100];
sprintf(sendBuf,"來自伺服器端",
inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[100];
recv(sockConn,recvBuf,100,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}
Ⅳ 在windows下用C語言如何實現socket網路編程,需要用到哪些頭文件或者庫
需要用到的頭文件包含:
#include <winsock2.h>
#include <windows.h>
與Linux環境下socket編程相比,windows環境多了一個步驟:啟動或者初始化winsock庫
Winsock,一種標准API,一種網路編程介面,用於兩個或多個應用程序(或進程)之間通過網路進行數據通信。具有兩個版本:
Winsock 1:
Windows CE平台支持。
頭文件:WinSock.h
庫:wsock32.lib
Winsock 2:
部分平台如Windows CE貌似不支持。通過前綴WSA可以區別於Winsock 1版本。個別函數如WSAStartup、WSACleanup、WSARecvEx、WSAGetLastError都屬於Winsock 1.1規范的函數;
頭文件:WinSock2.h
庫:ws2_32.lib
mswsock.h用於編程擴展,使用時必須鏈接mswsock.dll
(4)wsadata頭文件擴展閱讀
winsock庫的載入與卸載:
載入:int WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);
載入成功,返回值為0。
WORD wVersionRequested:載入的winsock版本,使用宏MAKEWORD(x, y),x表示高位元組,y表示低位元組。然而使用時MAKEWORD(2, 2)。高位元組與低位元組相同~~
LPWSADATA lpWSAData:WSADATA結構的指針,傳入參數後,系統幫助我們填充版本信息。有興趣的可以看看結構體內容,不過基本用不著。
卸載:int WSACleanup(void);比起載入,卸載的函數真是輕松愉快。
Ⅳ 如何實現基於ace庫的tcp/udp通信的封裝
類名:TSocket
文件包含:TSocket.cpp、TSocket.h
使用方法:
1、在對話框頭文件包含TSocket.h
#include "TSocket.h"
2、定義變數
TSocket m_TSocket;
3、TSocket類函數功能介紹:
LoadSocket():載入SOCKET庫
CreateSocketSer(TRUE):創建SOCKET,TRUE為TCP,FALSE為UDP
BingSocket():綁定IP和埠,有默認值
Start(precvPar):precvPar為一個RECVPARAM結構體指針
SendData(strSend):發送數據函數
4、服務端處理接收到的數據(消息映射、路由)
afx_msg void OnRecvData(WPARAM wParam,LPARAM lParam);
ON_MESSAGE(WM_RECVDATA,OnRecvData)
void CXXXDlg::OnRecvData( WPARAM wParam,LPARAM lParam )
{
CString strrecv = (char*)lParam;//得到消息內容
}
5、穩定性不能保證,僅供參考socket通信原理。。。。。。
****************************************TSocket.h*****************************************
// TSocket.h: interface for the TSocket class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TSOCKET_H__ECFF7A02_DCAF_455D_97C3_0C1D465D977B__INCLUDED_)
#define AFX_TSOCKET_H__ECFF7A02_DCAF_455D_97C3_0C1D465D977B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include
#pragma comment(lib,"ws2_32.lib")
#define WM_RECVDATA WM_USER+500 //定義接收到數據發出的消息號
#define MAX_MSG_LEN 1500 //最大的消息長度(MTU)
#define DEFAULTPORT 1991 //定義默認服務埠
class TSocket;
struct RECVPARAM
{
TSocket* psocket;//指定創建的socket
HWND hwnd;//指定需要處理接收消息的窗口句柄
};
class TSocket
{
public:
TSocket();
virtual ~TSocket();
public:
//載入Winsock庫
BOOL LoadSocket();
BOOL CreateSocketSer(BOOL bMode);//創建socket用於伺服器端
SOCKET CreateSocket(BOOL bMode);//創建socket用於客戶端
BOOL BingSocket(u_long ulIP=0,u_short usPort=DEFAULTPORT);//綁定埠、IP(默認所有IP)
BOOL Start(RECVPARAM* recvPar);
BOOL Stop();
SOCKET GetSocket();//得到當前socket
CString m_strData;//發出去的數據
BOOL m_bIsRun; //是否繼續運行
u_long m_ulLocalIP;//本地IP
u_short m_usLocalPort;//本地埠
u_long m_ulRemoteIP;//遠程IP
u_short m_usRemotePort;//遠程埠
//發送數據
DWORD SendData(CString strSend);
//TCP發送線程
static DWORD WINAPI TcpSendProc(LPVOID lpParameter);
//UDP發送線程
static DWORD WINAPI UdpSendProc(LPVOID lpParameter);
//TCP發送數據
DWORD TcpSend();
//UDP發送數據
DWORD UdpSend();
private:
BOOL m_bMode; //通信方式 1--TCP 0--UDP
SOCKET m_socket;//套接字
HANDLE m_hRecv; //接收線程的句柄
//TCP接收線程
static DWORD WINAPI TcpRecvProc(LPVOID lpParameter);
//UDP接收線程
static DWORD WINAPI UdpRecvProc(LPVOID lpParameter);
};
#endif // !defined(AFX_TSOCKET_H__ECFF7A02_DCAF_455D_97C3_0C1D465D977B__INCLUDED_)
****************************************TSocket.h*****************************************
****************************************TSocket.cpp*****************************************
// TSocket.cpp: implementation of the TSocket class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "TSocket.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
TSocket::TSocket()
{
m_bMode = FALSE;//UDP
m_ulRemoteIP = 0;
m_ulLocalIP = 0;
}
TSocket::~TSocket()
{
//釋放Winsock庫
WSACleanup();
}
BOOL TSocket::LoadSocket()
{
//載入Winsock庫
WSADATA wsa;
if (WSAStartup(MAKEWORD(1,1),&wsa) != 0)
{
return FALSE; //載入失敗
}
return TRUE;
}
BOOL TSocket::CreateSocketSer(BOOL bMode)
{
m_bMode = bMode;
//創建SOCKET
if (m_bMode)
{
m_socket = socket(AF_INET,SOCK_STREAM,0);//TCP流式
}else
{
m_socket = socket(AF_INET,SOCK_DGRAM,0);//UDP方式
}
return TRUE;
}
SOCKET TSocket::CreateSocket( BOOL bMode )
{
m_bMode = bMode;
SOCKET socketCr;
//創建SOCKET
if (m_bMode)
{
socketCr = socket(AF_INET,SOCK_STREAM,0);//TCP方式
}else
{
socketCr = socket(AF_INET,SOCK_DGRAM,0);//UDP方式
}
return socketCr;
}
BOOL TSocket::BingSocket(u_long ulIP,u_short usPort)
{
//配置監聽地址、綁定監聽埠
SOCKADDR_IN Sersock;//用於伺服器的監聽SOCKET
ZeroMemory(&Sersock,sizeof(Sersock));
if(ulIP==0)
{
Sersock.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
}else
{
Sersock.sin_addr.S_un.S_addr = htonl(ulIP);//IP
}
Sersock.sin_family = AF_INET;
Sersock.sin_port = htons(usPort);//埠號
int nbind = bind(m_socket,(SOCKADDR *)&Sersock,sizeof(SOCKADDR));
if (SOCKET_ERROR==nbind)
{
closesocket(m_socket);
return FALSE;
}
return TRUE;
}
DWORD WINAPI TSocket::TcpRecvProc( LPVOID lpParameter )
{
TSocket* psocket = ((RECVPARAM *)lpParameter)->psocket;
HWND hwnd = ((RECVPARAM *)lpParameter)->hwnd;
delete lpParameter;//釋放內存
listen(psocket->m_socket,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
char szrecvbuf[MAX_MSG_LEN];
char szsendBuf[50];
ZeroMemory(szrecvbuf,sizeof(szrecvbuf));
ZeroMemory(szsendBuf,sizeof(szsendBuf));
SOCKET sockSer;
while(psocket->m_bIsRun)
{
//用accept函數接收客戶方的連接
sockSer=accept(psocket->m_socket,(SOCKADDR*)&addrClient,&len);
if (INVALID_SOCKET==sockSer)
continue;
sprintf(szsendBuf,"Welcome %s to here!",inet_ntoa(addrClient.sin_addr));
//在客戶方套接字clientSocket上使用send發送數據
send(sockSer,szsendBuf,strlen(szsendBuf)+1,0);
//接收的數據
recv(sockSer,szrecvbuf,50,0);
psocket->m_strData.Format(_T("IP:%s,埠:%d 說:%s"),
inet_ntoa(addrClient.sin_addr),addrClient.sin_port,szrecvbuf);
::PostMessage(hwnd,WM_RECVDATA,0,(LPARAM)psocket->m_strData.GetBuffer(0));
//關閉本次連接
closesocket(sockSer);
//休息100S
Sleep(100);
}
//關閉socket
closesocket(psocket->m_socket);
return 0;
}
DWORD WINAPI TSocket::UdpRecvProc( LPVOID lpParameter )
{
TSocket* psocket = ((RECVPARAM *)lpParameter)->psocket;
HWND hwnd = ((RECVPARAM *)lpParameter)->hwnd;
delete lpParameter;//釋放內存
SOCKADDR_IN sockRecv;
int nlen = sizeof(SOCKADDR);
char szrecvbuf[MAX_MSG_LEN];
ZeroMemory(szrecvbuf,sizeof(szrecvbuf));
int nrecv;
while (psocket->m_bIsRun)
{
nrecv=recvfrom(psocket->m_socket,szrecvbuf,sizeof(szrecvbuf),0,(SOCKADDR *)&sockRecv,&nlen);
if (SOCKET_ERROR == nrecv)
break;
psocket->m_strData.Format(_T("IP:%s,埠:%d 說:%s"),
inet_ntoa(sockRecv.sin_addr),sockRecv.sin_port,szrecvbuf);
::PostMessage(hwnd,WM_RECVDATA,0,(LPARAM)psocket->m_strData.GetBuffer(0));
//休息100S
Sleep(1000);
}
//關閉socket
closesocket(psocket->m_socket);
CloseHandle(psocket->m_hRecv);
return 0;
}
BOOL TSocket::Start( RECVPARAM* recvPar )
{
m_bIsRun = TRUE;
//創建接收消息的線程
if (m_bMode)
{
m_hRecv = CreateThread(NULL,0,TcpRecvProc,(LPVOID)recvPar,0,NULL);
}else
{
m_hRecv = CreateThread(NULL,0,UdpRecvProc,(LPVOID)recvPar,0,NULL);
}
return TRUE;
}
BOOL TSocket::Stop()
{
//Kill線程???
if (m_hRecv!=NULL)
{
TerminateThread(m_hRecv,0);
//關閉socket
closesocket(m_socket);
}
m_bIsRun = FALSE;
return TRUE;
}
DWORD TSocket::TcpSend()
{
if (m_ulRemoteIP==0)
return -1;
SOCKET SocketSend;
SocketSend=CreateSocket(TRUE);
if (SocketSend==INVALID_SOCKET)
{
return -1;
}
SOCKADDR_IN SocketSendIn;
SocketSendIn.sin_family = AF_INET;
SocketSendIn.sin_addr.S_un.S_addr = htonl(m_ulRemoteIP);
SocketSendIn.sin_port = htons(m_usRemotePort);
char szBuf[50];
//先建立連接
int nRet = connect(SocketSend,(SOCKADDR*)&SocketSendIn,sizeof(SOCKADDR));
if (nRet==SOCKET_ERROR)
{
return -1;
}
nRet = recv(SocketSend,szBuf,sizeof(szBuf),0);
if (nRet==0)//超時
{
return -2;
}
//開始發送數據
send(SocketSend,m_strData.GetBuffer(0),m_strData.GetLength(),0);
closesocket(SocketSend);
return 0;
}
DWORD TSocket::UdpSend()
{
if (m_ulRemoteIP==0)
return -1;
SOCKET SocketSend;
SocketSend=CreateSocket(FALSE);
if (SocketSend==INVALID_SOCKET)
{
return -1;
}
SOCKADDR_IN SocketSendIn;
SocketSendIn.sin_family = AF_INET;
SocketSendIn.sin_addr.S_un.S_addr = htonl(m_ulRemoteIP);
SocketSendIn.sin_port = htons(m_usRemotePort);
int nSenlen=m_strData.GetLength()+1;
sendto(SocketSend,m_strData,nSenlen,0,(SOCKADDR *)&SocketSendIn,sizeof(SOCKADDR));
closesocket(SocketSend);
return 0;
}
DWORD TSocket::SendData( CString strSend )
{
//保存數據
m_strData = strSend;
if (m_bMode)
{
CreateThread(NULL,0,TcpSendProc,(LPVOID)this,0,NULL);
}else
{
CreateThread(NULL,0,UdpSendProc,(LPVOID)this,0,NULL);
}
return 0;
}
SOCKET TSocket::GetSocket()
{
return m_socket;
}
DWORD WINAPI TSocket::TcpSendProc( LPVOID lpParameter )
{
TSocket* pThis = (TSocket*)lpParameter;
return pThis->TcpSend();
}
DWORD WINAPI TSocket::UdpSendProc( LPVOID lpParameter )
{
TSocket* pThis = (TSocket*)lpParameter;
return pThis->UdpSend();
}
****************************************TSocket.cpp*************
本答案來自於互聯網,僅供參考學習作用
如果您對我的回答有不滿意的地方,還請您繼續追問;
答題不易,互相理解,互相幫助!