Ⅰ 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*************
本答案来自于互联网,仅供参考学习作用
如果您对我的回答有不满意的地方,还请您继续追问;
答题不易,互相理解,互相帮助!