众所周知:Linux作为服务器但安全可靠.所以尝试使用Linux作为服务器,Windows作为客户端的C/S简单架构.
直接上源码:
Linux下的服务器端文件.cpp,然后再用g++编译链接下就好了.
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<memory.h>
#include<string.h>
#include<sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
int main(){
int sock,new_sock;
struct sockaddr_in my_addr,client_addr;
socklen_t len;
char buf[100];
if((sock=socket(AF_INET,SOCK_STREAM,0))<0){
printf("socket create error!\n");
exit(1);
}
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(PORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
if(bind(sock,(struct sockaddr*)&my_addr,sizeof(my_addr))==-1){
printf("bind error!\n");
exit(1);
}
if(listen(sock,5)<0){
printf("listen error!\n");
exit(1);
}
len=sizeof(struct sockaddr);
new_sock=accept(sock,(struct sockaddr*)&client_addr,&len);
if(new_sock < 0){
printf("accept error!\n");
exit(1);
}else{
printf("server: get connection from %s,port %d socket %d \n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port),new_sock);
}
while(1){
memset(buf,0,100);
printf("Input message to send: ");
fgets(buf,100,stdin);
if(!strncasecmp(buf,"quit",4)){
printf("server is closing...\n");
break;
}
len=send(new_sock,buf,strlen(buf)-1,0);
if(len<0){
printf("send error!\n");
exit(1);
}else{
printf("send succeed! send : %s\n",buf);
}
printf("------------------------------\n");
memset(buf,0,100);
len=recv(new_sock,buf,100,0);
if(len<0){
printf("recv error!\n");
exit(1);
}else if(len == 0){
printf("the client quit!\n");
break;
}else{
printf("receive message: %s \n",buf);
}
}
close(sock);
close(new_sock);
}
Win作为客户端的代码:
// MySocket.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
int _tmain(int argc, _TCHAR* argv[])
{//初始化socket编程环境
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
{
return 0;
}
if (LOBYTE(wsaData.wVersion) != 1 ||
HIBYTE(wsaData.wVersion) != 1)
{
WSACleanup();
return 0;
}
//建立客户端socket
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
//服务器地址
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("119.29.176.220");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8888);
//连接服务器
//等待接收服务器的响应
char recvBuf[100];
memset(recvBuf, 0, 100);
connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
int r = 0;
do//不断与服务器连接,直到它关闭
{
printf("receiving.....\n");
r = recv(sockClient, recvBuf, 100, 0);
printf("receive end.....\n");
printf("data from server: %s\n", recvBuf);
char sendBuf[100];
printf("input the message to send[1-100]: ");
gets(sendBuf);
printf("sending.....\n");
r = send(sockClient, sendBuf, strlen(sendBuf) + 1, 0);
printf("send ended. waiting for server\n");
} while (r != SOCKET_ERROR);
printf("server connect error! app will exit\n");
system("PAUSE");
closesocket(sockClient);
WSACleanup();
return 0;
}
实现效果: