MyException - 我的异常网
当前位置:我的异常网» 操作系统 » Socket缂栫▼瀹炵幇澶氫汉鑱婂ぉ瀹?C璇█鐗

Socket缂栫▼瀹炵幇澶氫汉鑱婂ぉ瀹?C璇█鐗

www.MyException.Cn  网友分享于:2013-12-09  浏览:0次
Socket缂栫▼瀹炵幇澶氫汉鑱婂ぉ瀹?C璇█鐗?

聽聽聽聽聽聽 socket缂栫▼鑺变簡鎴戜笁鍥涘ぉ鐨勪簨浠剁粓浜庡皢杩欎釜绋嬪簭缁欏疄鐜颁簡澶х瑧澶х瑧

聽聽聽聽聽 鎵€璋撶殑澶氫汉鑱婂ぉ瀹わ紝鍏跺疄涓嶈繃鏄鎴风鍒涘缓涓€涓暟鎹帴鏀剁嚎绋嬪拰鏁版嵁鍙戦€佺嚎绋嬶紝鑰屽湪鏈嶅姟鍣ㄧ鍒涘缓涓€涓鎺ュ瓧鏁扮粍锛屽紑鍚竴涓帴鍙楄繛鎺ヨ姹傜嚎绋嬶紝涓嶆柇鎺ュ彈鏉ヨ嚜瀹㈡埛绔殑杩炴帴璇锋眰锛岀劧鍚庡皢寤虹珛鐨勮繛鎺ユ墍褰㈡垚鐨勬柊濂楁帴瀛楁弿杩扮瀛樿繘濂楁帴瀛楁暟缁勶紝骞堕拡瀵规墍瀛樺偍鐨勫鎺ュ瓧鎻忚堪绗﹀缓绔嬪涓暟鎹帴鏀剁嚎绋嬶紝瀵逛簬鎵€鎺ユ敹鍒扮殑鏁版嵁锛屽紑鍚竴涓暟鎹浆鍙戣繘绋嬶紝瀵瑰鎺ュ瓧鏁扮粍涓殑姣忎釜瀹㈡埛绔皢鏀跺埌鐨勬暟鎹繘琛岃浆鍙戙€傛湇鍔″櫒灏辨槸璧峰埌杩欎釜涓€涓暟鎹浆鍙戠殑鍔熻兘銆?/p>

闄勪笂浠g爜

瀹㈡埛绔細

#include <stdio.h>
#include <winsock2.h>
#include <pthread.h>
#pragma comment(lib,"ws2_32.lib")
char buffer[4096] = {0};
int iRecvLen = 0;
int iSnedLen = 0;
char name[20];
void  THRE_RECV(SOCKET ClientSocket)
{
    char buffer[50]={0};
    while(1)
    {
        memset(buffer, 0, sizeof(buffer));///鎺ユ敹娑堟伅

        iRecvLen = recv(ClientSocket, buffer, sizeof(buffer), 0);
        if (SOCKET_ERROR == iRecvLen)
        {
            printf("send failed with error code: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return -1;
        }
        ///printf("recv %d bytes from %s: ", iRecvLen, nameOther);//涓轰簡缇庤鏈€濂戒笉瑕佹墦鍗拌繖涓簡
        //strcat(buffer, "\0");
        buffer[iRecvLen] = 0;
        printf("\n%s\n", buffer);
    }
}

int main()
{
     WSADATA wsaData = { 0 };///瀛樻斁濂楁帴瀛椾俊鎭?WSADATA缁撴瀯琚敤鏉ヤ繚瀛楢fxSocketInit鍑芥暟杩斿洖鐨刉indowsSockets鍒濆鍖栦俊鎭€?
    SOCKET ClientSocket = INVALID_SOCKET;///瀹㈡埛绔鎺ュ瓧
    ///printf("%d\n",INVALID_SOCKET);
    SOCKADDR_IN ServerAddr = { 0 };///鏈嶅姟绔湴鍧€
    USHORT uPort = 18000;///鏈嶅姟绔鍙?

    ///鍒濆鍖栧鎺ュ瓧
    if(WSAStartup(MAKEWORD(2,2), &wsaData))///璇ュ嚱鏁扮殑绗竴涓弬鏁版寚鏄庣▼搴忚姹備娇鐢ㄧ殑Socket鐗堟湰锛屽叾涓珮浣嶅瓧鑺傛寚鏄庡壇鐗堟湰銆佷綆浣嶅瓧鑺傛寚鏄庝富鐗堟湰
    ///绗簩涓弬鏁拌繑鍥炶姹傜殑socket鐗堟湰淇℃伅
    {
        printf("WSAStartup failed with error code: %d\n", WSAGetLastError());
        return -1;
    }
    ///鍒ゆ柇濂楁帴瀛楃増鏈?
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        printf("wVersion was not 2.2\n");
        return -1;
    }
    ///鍒涘缓濂楁帴瀛?
    ClientSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);///AF_INET浠h〃涓€涓湴鍧€鏃?SOCK_STREAM琛ㄧず涓篢CP鍗忚鐨勬祦鏈嶅姟,IPPROTO_TCP鐨勫€间负6
    ///printf("%d\n",IPPROTO_TCP);
    if (ClientSocket == INVALID_SOCKET)
    {
        printf("socket鍒濆鍖栧け璐ュ苟杩斿洖閿欒浠g爜: %d\n", WSAGetLastError());
        return -1;
    }
    ///杈撳叆鏈嶅姟鍣↖P
    printf("Please input the server's IP:");
    char IP[32] = { 0 };
    gets(IP);
    ///杈撳叆鑱婂ぉ鐨勭敤鎴峰悕
    printf("Please input the Client's username:");
    char name[32] = {0};
    memset(name,0,sizeof(name));
    gets(name);
    ///璁剧疆鏈嶅姟鍣ㄥ湴鍧€锛屽~鍏呮湇鍔″櫒鍦板潃鐨勭粨鏋?
    ServerAddr.sin_family = AF_INET;
    ServerAddr.sin_port = htons(uPort);///鏈嶅姟鍣ㄧ鍙?
    ServerAddr.sin_addr.S_un.S_addr = inet_addr(IP);///鏈嶅姟鍣ㄥ湴鍧€

    printf("Connecting...........\n");
    ///杩炴帴鏈嶅姟鍣?
    if(SOCKET_ERROR == connect(ClientSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)))
    {
        printf("Connect failed with error code: %d \n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return -1;
    }
    printf("Successfuuly got a connection from IP:%s Port:%d\n\n\n\n",inet_ntoa(ServerAddr.sin_addr),htons(ServerAddr.sin_port));
    _beginthreadex(NULL,0,&THRE_RECV,ClientSocket,NULL,0);
    iSnedLen = send(ClientSocket,name,strlen(name),0);
    if(SOCKET_ERROR == iSnedLen)
    {
        printf("send failed with error code: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return -1;
    }
    while(1)
    {
        memset(buffer, 0, sizeof(buffer));
        ///鍙戦€佹秷鎭?

        gets(buffer);
        if(strcmp(buffer,"bye") == 0) break;
        printf("%s: ", name);
        iSnedLen = send(ClientSocket, buffer, strlen(buffer), 0);
        if (SOCKET_ERROR == iSnedLen)
        {
            printf("send failed with error code: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return -1;
        }
    }
    closesocket(ClientSocket);
    WSACleanup();
    system("pause");
    return 0;
}

聽鏈嶅姟鍣ㄧ锛?/p>

#include <WinSock2.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma comment(lib,"ws2_32.lib")

#define SEND_OVER 1                          ///宸茬粡杞彂娑堟伅
#define SEND_YET  0                          ///杩樻病杞彂娑堟伅

typedef struct _Client
{
    SOCKET sClient;      ///瀹㈡埛绔鎺ュ瓧
    char buf[128];       ///鏁版嵁缂撳啿鍖?
    char userName[16];   ///瀹㈡埛绔敤鎴峰悕
    char IP[20];         ///瀹㈡埛绔疘P
    UINT_PTR flag;       ///鏍囪瀹㈡埛绔紝鐢ㄦ潵鍖哄垎涓嶅悓鐨勫鎴风
    int first;
}Client;

Client g_Client[10] = { 0 };

int  SENDFFFF = 0;
int  Rflag = 0;

SOCKADDR_IN ServerAddr = { 0 };///鏈嶅姟绔湴鍧€
SOCKADDR_IN ClientAddr = { 0 };///瀹㈡埛绔湴鍧€
int iClientAddrLen = sizeof(ClientAddr);
SOCKET g_ServerSocket = INVALID_SOCKET;      ///鏈嶅姟绔鎺ュ瓧
SOCKADDR_IN g_ClientAddr = { 0 };            ///瀹㈡埛绔湴鍧€
int g_iClientAddrLen = sizeof(g_ClientAddr);
USHORT uPort = 18000;                       ///鏈嶅姟鍣ㄧ洃鍚鍙?
unsigned __stdcall ThreadSend(void* param)
{
    while(1)
    {
        if(SENDFFFF==0) continue;
        else
        {
            SOCKET client = INVALID_SOCKET;                 ///鍒涘缓涓€涓复鏃跺鎺ュ瓧鏉ュ瓨鏀捐杞彂鐨勫鎴风濂楁帴瀛?
            char temp[128];
            memset(temp,0,sizeof(temp));                        ///鍒涘缓涓€涓复鏃剁殑鏁版嵁缂撳啿鍖猴紝鐢ㄦ潵瀛樻斁鎺ユ敹鍒扮殑鏁版嵁
            memcpy(temp, g_Client[Rflag].buf, sizeof(temp));
            printf("temp = %s\n",temp);
            int k = 1;
            while(k<=5)
            {
                if(k!=Rflag)
                {
                     sprintf(g_Client[k].buf, "%s: %s", g_Client[Rflag].userName, temp);///娣诲姞涓€涓敤鎴峰悕澶?
                }
                k++;
            }
            k=1;
            while(k<=5)
            {
                if(strlen(temp) != 0&&g_Client[k].sClient!=INVALID_SOCKET&&k!=Rflag)
                {
                    int ret = send(g_Client[k].sClient, g_Client[k].buf, strlen(g_Client[k].buf), 0);
                    printf("g_Client[k].buf == .............%s\n",g_Client[k].buf);
                    if(ret==SOCKET_ERROR) return 1;
                }
                k++;
            }
            Rflag = 0;
            SENDFFFF = 0;
        }
    }

    return 0;
}

unsigned __stdcall THREAD_RECV(SOCKET ClientSocket)
{
    int flag = 0;
    int u = 1;
    while(u<=5)
    {
        if(g_Client[u].sClient==ClientSocket&&g_Client!=INVALID_SOCKET)
        {
            flag = u;
        }
      u++;
    }
    printf("flag = %d\n",flag);
    char temp[80] = {0};
    while(1)
    {
        memset(temp, 0, sizeof(temp));
        int ret = recv(ClientSocket, temp, sizeof(temp), 0); ///鎺ユ敹鏁版嵁
        printf("%s\n",temp);
        if (ret == SOCKET_ERROR)
        {
                printf("ClientSocket=%d  error=%d",ClientSocket,errno);
                //getchar();
                continue;
        }

            //iStatus = SEND_YET;                                ///璁剧疆杞彂鐘舵€佷负鏈浆鍙?
        //flag = client == g_Client[0].sClient ? 1 : 0;        ///杩欎釜瑕佽缃紝鍚﹀垯浼氬嚭鐜拌嚜宸辩粰鑷繁鍙戞秷鎭殑BUG
        int k = 1;
        while(k<=5)
        {
            if(k!=flag&&g_Client[flag].first==1)
                memcpy(g_Client[k].buf, temp, strlen(g_Client[k].buf));
            printf("%s\n",g_Client[k].buf);
            k++;
        }
        if(g_Client[flag].first==0)///濡傛灉杩欐槸绗竴娆′紶杩囨潵鐨勬暟锛岃鏄庤繖鏄竴涓敤鎴峰悕锛屼笉闇€瑕佽繘琛岃浆鍙戯紝灏嗗叾澶嶅埗鍒拌鐩稿簲鐨勭敤鎴峰悕褰撲腑
        {
            memcpy(g_Client[flag].userName,temp,sizeof(temp));
            g_Client[flag].first = 1;
        }
        else
        {
            Rflag = flag;
            SENDFFFF = 1; ///寮€鍚竴涓浆鍙戠嚎绋?flag鏍囪鐫€瑕佽浆鍙戠粰鍝釜瀹㈡埛绔?
        }
    }
}
unsigned __stdcall THREAD_ACCEPT(SOCKET ClientSocket)
{

    int num = 0;
    while(1)
    {
        num = 0;
        int  k = 1;
       while(k<=5)
       {
        if(g_Client[k].sClient!=INVALID_SOCKET)
        {
            num++;
            k++;
            continue;
        }
        else
        {
            g_Client[k].sClient = accept(ClientSocket, (SOCKADDR*)&g_ClientAddr, &g_iClientAddrLen);
            if(g_Client[k].sClient == INVALID_SOCKET)
            {
                printf("accept failed with error code: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return -1;
            }
            //int len = recv(g_Client[k].sClient, g_Client[k].userName, 15, 0); ///鎺ユ敹鐢ㄦ埛鍚?
            //g_Client[k].userName[len]=0;
            //printf("\nlen = %d\n",len);
            printf("Successfuuly got a connection from IP:%s ,Port: %d,UerName: %s\n",inet_ntoa(g_ClientAddr.sin_addr), htons(g_ClientAddr.sin_port), g_Client[k].userName);
            //printf("%s\n",g_Client[k].sClient);
            printf("k = %d\n",k);
            memcpy(g_Client[k].IP, inet_ntoa(g_ClientAddr.sin_addr), sizeof(g_Client[k].IP)); ///璁板綍瀹㈡埛绔疘P
            g_Client[k].flag = g_Client[k].sClient; ///涓嶅悓鐨剆ocke鏈変笉鍚孶INT_PTR绫诲瀷鐨勬暟瀛楁潵鏍囪瘑
            num++;
            k++;
            break;
        }
      }
      //printf("num = %d\n",num);
      if(num>=3)
      {
          int l =1;
          while(l<=5)
          {
              if(g_Client[l].sClient!=INVALID_SOCKET)
              {
                  _beginthreadex(NULL,0,&THREAD_RECV,g_Client[l].sClient,0,0);
              }
              l++;
          }
      }


    }
}


int main()
{
    ///瀛樻斁濂楁帴瀛椾俊鎭殑缁撴瀯
    WSADATA wsaData = { 0 };
    SOCKET ServerSocket = INVALID_SOCKET;///鏈嶅姟绔鎺ュ瓧
    SOCKET ClientSocket = INVALID_SOCKET;///瀹㈡埛绔鎺ュ瓧
    int pp = 1;
    while(pp<=6)
    {
        memset(g_Client[pp].buf,0,sizeof(g_Client[pp].buf));
        g_Client[pp].first = 0;
        memset(g_Client[pp].IP,0,sizeof(g_Client[pp].IP));
        g_Client[pp].sClient = INVALID_SOCKET;
        memset(g_Client[pp].userName,0,sizeof(g_Client[pp].userName));
        pp++;
    }

    if (WSAStartup(MAKEWORD(2, 2), &wsaData))
    {
        printf("WSAStartup failed with error code: %d\n", WSAGetLastError());
        return -1;
    }
    ///鍒ゆ柇鐗堟湰
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        printf("wVersion was not 2.2\n");
        return -1;
    }
    ///鍒涘缓濂楁帴瀛?
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
    {
        printf("socket failed with error code: %d\n", WSAGetLastError());
        return -1;
    }

    ///璁剧疆鏈嶅姟鍣ㄥ湴鍧€
    ServerAddr.sin_family = AF_INET;///杩炴帴鏂瑰紡
    ServerAddr.sin_port = htons(uPort);///鏈嶅姟鍣ㄧ洃鍚鍙?
    ServerAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);///浠讳綍瀹㈡埛绔兘鑳借繛鎺ヨ繖涓湇鍔″櫒
    ///鍒濆鍖栧鎺ュ瓧
                                                        ///缁戝畾鏈嶅姟鍣?
    if (SOCKET_ERROR == bind(ServerSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)))
    {
        printf("bind failed with error code: %d\n", WSAGetLastError());
        closesocket(ServerSocket);
        return -1;
    }
    ///鐩戝惉鏈夋棤瀹㈡埛绔繛鎺?
    if (SOCKET_ERROR == listen(ServerSocket, 1))
    {
        printf("listen failed with error code: %d\n", WSAGetLastError());
        closesocket(ServerSocket);
        WSACleanup();
        return -1;
    }
     _beginthreadex(NULL, 0, ThreadSend, NULL,0,NULL);
     _beginthreadex(NULL,0,&THREAD_ACCEPT,ServerSocket,NULL,0);
     int k = 0;
    while(k<100)///璁╀富绾跨▼浼戠湢锛屼笉璁╁畠鍏抽棴TCP杩炴帴.
    {
         Sleep(10000000);
         k++;
    }

    ///鍏抽棴濂楁帴瀛?
    int j = 1;
    while(j<6)
    {
        if (g_Client[j].sClient != INVALID_SOCKET)
            closesocket(g_Client[j].sClient);
        j++;
    }
    closesocket(g_ServerSocket);
    WSACleanup();
    return 0;
    /*
    ClientSocket = accept(ServerSocket, (SOCKADDR*)&ClientAddr, &iClientAddrLen);///accept涓洪樆濉炲嚱鏁?
    if (ClientSocket == INVALID_SOCKET)
    {
        printf("accept failed with error code: %d\n", WSAGetLastError());
        closesocket(ServerSocket);
        WSACleanup();
        return -1;
    }
    printf("Successfuuly got a connection from IP:%s Port:%d\n\n\n\n",inet_ntoa(ClientAddr.sin_addr),htons(ClientAddr.sin_port));

*/



}

瀵逛簬浠g爜鐨勬€濊矾鍜屾敞閲婇兘鍐欏湪浠g爜閲岄潰浜嗭紝甯屾湜杩欎釜鏂囨。瀵逛簬鍒氬涔犵綉缁滅紪绋嬬殑浜烘湁鎵€甯姪銆?/p>

聽涓嶈繃杩欎釜绋嬪簭鏈変竴涓棶棰樺氨鏄湪瀹㈡埛绔柇寮€杩炴帴鐨勬椂鍊欎細鍑虹幇閿欒锛岃繕鏈夊緟瑙e喅锛侊紒鍙互瀵规瘡涓鎴风鐨勮繛鎺ュ缓绔嬩竴涓嚎绋嬭繘琛屽崟鐙殑寰幆鏌ヨ锛屽綋妫€娴嬪埌鍏舵柇寮€鏃跺鍏惰繘琛屽叧闂鎺ュ瓧锛屽叧闂浉搴旂殑绾跨▼銆?/p>

文章评论

10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
一个程序员的时间管理
一个程序员的时间管理
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
看13位CEO、创始人和高管如何提高工作效率
看13位CEO、创始人和高管如何提高工作效率
如何区分一个程序员是“老手“还是“新手“?
如何区分一个程序员是“老手“还是“新手“?
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
2013年美国开发者薪资调查报告
2013年美国开发者薪资调查报告
我跳槽是因为他们的显示器更大
我跳槽是因为他们的显示器更大
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
做程序猿的老婆应该注意的一些事情
做程序猿的老婆应该注意的一些事情
如何成为一名黑客
如何成为一名黑客
中美印日四国程序员比较
中美印日四国程序员比较
什么才是优秀的用户界面设计
什么才是优秀的用户界面设计
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
旅行,写作,编程
旅行,写作,编程
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
老美怎么看待阿里赴美上市
老美怎么看待阿里赴美上市
10个调试和排错的小建议
10个调试和排错的小建议
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
Java程序员必看电影
Java程序员必看电影
程序员和编码员之间的区别
程序员和编码员之间的区别
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
程序员都该阅读的书
程序员都该阅读的书
为什么程序员都是夜猫子
为什么程序员都是夜猫子
科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
每天工作4小时的程序员
每天工作4小时的程序员
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
代码女神横空出世
代码女神横空出世
不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
我的丈夫是个程序员
我的丈夫是个程序员
程序员必看的十大电影
程序员必看的十大电影
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
老程序员的下场
老程序员的下场
团队中“技术大拿”并非越多越好
团队中“技术大拿”并非越多越好
那些争议最大的编程观点
那些争议最大的编程观点
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
 程序员的样子
程序员的样子
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
2013年中国软件开发者薪资调查报告
2013年中国软件开发者薪资调查报告
Java 与 .NET 的平台发展之争
Java 与 .NET 的平台发展之争
程序猿的崛起——Growth Hacker
程序猿的崛起——Growth Hacker
编程语言是女人
编程语言是女人
漫画:程序员的工作
漫画:程序员的工作
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
程序员的鄙视链
程序员的鄙视链
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
鲜为人知的编程真相
鲜为人知的编程真相
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有