socket cs模型基礎架構

socket cs模型基礎架構,server及client

基本介紹

  • 中文名:套接字
  • 外文名:socket
Client,server,

Client

源碼
#include "stdafx.h"
#include <Winsock2.h>
#pragma comment(lib,"ws2_32")
#include <stdio.h>
#define PORT 1129
#define ADDRESS "127.0.0.1"
int main()
{
//載入winsock庫
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2,2);
if(WSAStartup(sockVersion,&wsaData)!=0)
return 0;
//創建套接字
SOCKET sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sClient==INVALID_SOCKET)
{
printf("socket error\n");
return 0;
}
//socket中裝入遠程地址信息
SOCKADDR_IN remote;
remote.sin_family = AF_INET;
remote.sin_port = htons(1129);
remote.sin_addr.S_un.S_addr = inet_addr(ADDRESS);
if(connect(sClient,(SOCKADDR *)&remote,sizeof(SOCKADDR))==SOCKET_ERROR)
{
printf("connect error\n");
closesocket(sClient);
return 0;
}
while(true)
{
char SendData[255];
int i,ch;
for( i = 0; (i < 254) && ((ch = getchar()) != EOF) && (ch!='\n'); i++)
SendData[i] = (char)ch;
SendData[i] = '\n';
SendData[i+1] = '\0';
send(sClient,SendData,i+2,0);
}
closesocket(sClient);
WSACleanup();
return 0;
}

server

源碼
// sssss.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Winsock2.h>
#pragma comment(lib,"ws2_32")
#include <stdio.h>
int main(int argc,char *[])
{
//載入winsock庫
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2,2);
if(WSAStartup(sockVersion,&wsaData)!=0)
return 0;
//創建套接字
SOCKET sServer = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sServer==INVALID_SOCKET)
{
printf("socket error\n");
return 0;
}
//socket中裝入地址信息
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(1129);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
//bind套接字
if(bind(sServer,(LPSOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR)
{
printf("bind error!\n");
return 0;
}
//listen模式
if(listen(sServer,5) == SOCKET_ERROR)
{
printf("listen error!\n");
closesocket(sServer);
return 0;
}
//循環接受連線請求
sockaddr_in remoteAddr;
SOCKET sClient;
int nAddrLen=sizeof(SOCKADDR_IN);
char revData[255];
while(1)
{
sClient = accept (sServer,(SOCKADDR*)&remoteAddr,&nAddrLen);
if(sClient==INVALID_SOCKET)
{
printf("accept error\n");
continue;
}
printf("接受來自%s的連線.\n",inet_ntoa(remoteAddr.sin_addr));
while(true)
{
int ret = recv(sClient,revData,255,0);
if(ret==0||(ret==SOCKET_ERROR&&WSAGetLastError()==WSAECONNRESET))
{
printf("%s關閉連線\n",inet_ntoa(remoteAddr.sin_addr));
closesocket(sClient);
break;
}
else
{
revData[ret]='\0';
printf("%s",revData);
}
}
}
closesocket(sServer);
WSACleanup();
return 0;
}

相關詞條

熱門詞條

聯絡我們