//windows TCP Client
# include "winsock2.h"
void main(void)
{
WSADATA wsaData
SOCKET s
SOCKADDR_IN ServerAddr
int Port = 80
//初始化Windows Socket 2.2
WSAStartup(MAKEWORD(2,2),wsaData)
// 创建一个新的Socket来连接服务器
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
// 填写客户端地址信息
// 端口为80
// 服务器IP地址为"192.168.1.1",注意使用inet_addr将IP地址转换为网络格式
ServerAddr.sin_family = AF_INET
ServerAddr.sin_port = htons(Port)
ServerAddr.sin_addr.s_addr = inet_addr("192.168.1.1")
// 向服务器发出连接请求
connect(s, (SOCKADDR *) &ampServerAddr, sizeof(ServerAddr))
// 新的连接建立后,就可以互相通信了,在这个简单的例子中,我们直接关闭连接,
// 并关闭监听Socket,然后退出应用程序
closesocket(s)
// 释放Windows Socket DLL的相关资源
WSACleanup()
}
#include <stdio.h>#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
void main() {
// 初始化
WSADATA wsaData
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData )
if ( iResult != NO_ERROR )
printf("Error at WSAStartup()\n")
// 建立socket
SOCKET server
server = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP )
if ( server == INVALID_SOCKET ) {
printf( "Error at socket(): %ld\n", WSAGetLastError() )
WSACleanup()
return
}
// 绑定socket
sockaddr_in service
service.sin_family = AF_INET
service.sin_addr.s_addr = inet_addr( "127.0.0.1" )
service.sin_port = htons( 27015 )
if ( bind( server, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
printf( "bind() failed.\n" )
closesocket(server)
return
}
// 监听 socket
if ( listen( server, 1 ) == SOCKET_ERROR )
printf( "Error listening on socket.\n")
// 接受连接
SOCKET AcceptSocket
printf( "Waiting for a client to connect...\n" )
while (1) {
AcceptSocket = SOCKET_ERROR
while ( AcceptSocket == SOCKET_ERROR ) {
AcceptSocket = accept( server, NULL, NULL )
}
printf( "Client Connected.\n")
server = AcceptSocket
break
}
// 发送接受数据
int bytesSent
int bytesRecv = SOCKET_ERROR
char sendbuf[32] = "Server: Sending Data."
char recvbuf[32] = ""
bytesRecv = recv( server, recvbuf, 32, 0 )
printf( "Bytes Recv: %ld\n", bytesRecv )
bytesSent = send( server, sendbuf, strlen(sendbuf), 0 )
printf( "Bytes Sent: %ld\n", bytesSent )
return
}
SERVER的
网络的Socket数据传输是一种特殊的I/O,Socket也是一种文件描述符。Socket也具有一个类似于打开文件的函数调用Socket(),该函数返回一个整型的Socket描述符,随后的连接建立、数据传输等操作都是通过该Socket实现的。下面用Socket实现一个windows下的c语言socket通信例子,这里我们客户端传递一个字符串,服务器端进行接收。
【服务器端】
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#include <winsock2.h>
#define SERVER_PORT 5208 //侦听端口
void main()
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)