因为这学期要交winsocket的通信程序,一个字,坑。因为上课就没有教的。不过有神器在手,陆楠同学的《计算机网络实训和编程》,so,还不是手到擒来!
环境:win7+vs2010
项目:C++项目,有预编译头文件
先看效果:
连接后:
看看client的源文件:
// TCPEx_Client.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
const int DEFAULT_PORT = 5000;
WORD wVersionRequested;
WSADATA wsaData;
int err,iLen;
if (argc < 2) {
cout<<"Command:TcpEx_Client ServerIP"<
再看Sever:
// TCPSrvEx.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#include
using namespace std;
#pragma comment(lib, "ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[]) {
const int DEFAULT_PORT = 5000;
WORD wVersionRequested;
WSADATA wsaData;
int err,iLen;
wVersionRequested=MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
cout<<"加载WinSock失败!";
return 0;
}
SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0); //创建服务器监听套接字
if (sockSrv == INVALID_SOCKET) {
cout<<"socket() fail:"<
好吧,其实我只是把书本上的例子实现了一遍。
看看老师给的例子:
client:
// Client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
void main(int argc, char* argv[])
{
SOCKET sock ;
SOCKADDR_IN dest_sin ;
WSADATA wsaData ;//版本参数
int port = 344 ;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
cout<<"WinSock startup Error!" ;
return ;
}
sock = socket(AF_INET, SOCK_STREAM, 0) ;
if (sock == INVALID_SOCKET) {
cout<<"socket() failed" ;
closesocket(sock) ;
return ;
}
dest_sin.sin_family = AF_INET ;
dest_sin.sin_port = htons(port) ;
dest_sin.sin_addr.s_addr = inet_addr("127.0.0.1") ;
connect(sock, (sockaddr *)&dest_sin, sizeof(dest_sin)) ;
////连续发十个数给服务器
char szName[20] ;
for(int i=0 ; i<20 ; i++)
{
sprintf(szName, " %d", i) ;
send(sock, szName, 20, 0) ;
}
// send(sock, " ",0,0) ;
closesocket(sock) ;
if (WSACleanup() == SOCKET_ERROR) {
cout<<"WSACleanup() failed with error "<
Sever:
// Server.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
#pragma comment(lib,"ws2_32.lib")
void main(int argc, char* argv[])
{
SOCKET sockServer ;
SOCKET sockAccept ;
SOCKADDR_IN local_sin ;
SOCKADDR_IN acc_sin ;
WSADATA wsaData ;
int port = 344 ;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
cout<<"WinSock startup Error!" ;
return ;
}
sockServer = socket(AF_INET, SOCK_STREAM, 0) ;
if (sockServer == INVALID_SOCKET) {
cout<<"socket() failed" ;
closesocket(sockServer) ;
return ;
}
local_sin.sin_port = htons(port) ;
local_sin.sin_family = AF_INET ;
local_sin.sin_addr.s_addr = INADDR_ANY ;
if (bind(sockServer, (sockaddr FAR*)&local_sin, sizeof(local_sin)) == SOCKET_ERROR) {
cout<<"bind(sock) failed "<