计算器操作远程监控程序

类别:编程语言 点击:0 评论:0 推荐:

// ser.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <Winsock2.h>
#include <stdio.h>
#include <stdlib.h>

#define PORT 5050
#define SER_DATA_BUFFER 4096

DWORD WINAPI ClientThread(LPVOID lpParam);

void main()
{
 HANDLE hThread;
 DWORD dwThreadId;
 SOCKET sClient;
 int iPort=PORT;
 WSADATA wsaData;
 SOCKET sListen;
 int iCliLen;
 
 char SerRecvBuf[SER_DATA_BUFFER]="";
 struct sockaddr_in ser,cli;
 
 printf("************************\n");
 printf("计算器操作远程监控程序:\n");
 
 if (WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
 {
  printf("Failed to load Winsock.\n");
  return;
 }
 sListen=socket(AF_INET,SOCK_STREAM,0);
 if (sListen==INVALID_SOCKET)
 {
  printf("socket() Failed:%d\n",WSAGetLastError());
  return;
 }
 
 ser.sin_family=AF_INET;
 ser.sin_port=htons(iPort);
 ser.sin_addr.s_addr=htonl(INADDR_ANY);
 
 if (bind(sListen,(LPSOCKADDR)&ser,sizeof(ser))==SOCKET_ERROR)
 {
  printf("bind() Failed:%d\n",WSAGetLastError());
  return;
 }
 
 listen(sListen,8);
 printf("************************\n");
 printf("等待连接:\n");
 printf("************************\n");
 
 while(1)
 {
  iCliLen=sizeof(cli);
  sClient=accept(sListen,(struct sockaddr*)&cli,&iCliLen);
  if(sClient==INVALID_SOCKET)
  {
   printf("accept() Failed:%d\n",WSAGetLastError());
   break;
  }
  printf("************************\n");
  printf("连接成功:\n");
  printf("************************\n");
  printf("客户端IP:[%s]\n客户端端口:[%d]\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
  printf("************************\n");

  hThread=CreateThread(NULL,0,ClientThread,(LPVOID)sClient,0,&dwThreadId);
  if (hThread==NULL)
   break;
  CloseHandle(hThread);
 }
 
 closesocket(sListen);
 WSACleanup();
}
  
DWORD WINAPI ClientThread(LPVOID lpParam)
{
 SOCKET ThreadSock=(SOCKET)lpParam;
 char szBuff[200];
 int recvlen;
 while(1)
 {
  recvlen=recv(ThreadSock,szBuff,200,0);
  if (recvlen==0)
  break;

  else if(recvlen==SOCKET_ERROR)
  {
   printf("************************\n");
   printf("连接断开:%d\n",WSAGetLastError());
   printf("************************\n");
   printf("等待连接:\n");
   printf("************************\n");
   break;
  }
  szBuff[recvlen]='\0';
  printf("%s",szBuff);
  printf(" ");
 }
 return 0;
}

本文地址:http://com.8s8s.com/it/it23398.htm