tcp网络编程(C语言)

tcp网络编程(C语言),第1张

以下是两个文件陵皮.client.c和server.c

server.c

client.c

运行效果伍历如尺橘差下

你的client有问题,连接之前没裂指有指定server的ip。

你只数颤指定了端肆毕配口。

struct sockaddr_in servaddr

bzero(&servaddr,sizeof(servaddr))

servaddr.sin_family=AF_INET

servaddr.sin_port=htons(HELLO_WORLD_SERVER_PORT)

servaddr.sin_addr.s_addr=inet_addr(serverip)//加上server的ip即可

#include

#include

#include

#pragma comment(lib,"ws2_32.lib")

typedef struct{

SOCKET accpt

int lock

}Arg

void *transfer(void *arg)

{

Arg * info = (Arg *)arg

SOCKET clientSock

char recvbuf[102]

char sendBuf[] = "10"

int ret

memcpy(&clientSock,(void*)&info->accpt,sizeof(clientSock))

info->lock =1

while (TRUE)

{

ret = send(clientSock,sendBuf,2,0)

if (ret == -1)

{

break

}

ret = recv(clientSock,recvbuf,102,0)

printf("%s\n",recvbuf)

}

return (void *)0

}

void* timer(void *arg)

{

time_t last = time(NULL)

time_t now

int i = 20

while(i--)

{

now = time(NULL)

if(now - last == 1)

{

printf("1s past!\n")

last = now

}

Sleep(500)

}

printf("timer exit.\n")

return (void *)0

}

int main(void) {

WSADATA wsaData

SOCKET ListenSocket

SOCKADDR_IN service,client

int len = sizeof(client)

Arg argument

pthread_t tid

char sendBuf[] = "ID=2WHAT=host"碰则蚂

int iResult = WSAStartup(MAKEWORD(2,2), &wsaData)

if (iResult != NO_ERROR) {

printf("Error at WSAStartup()\n")

return 1

}

ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)

if (ListenSocket == INVALID_SOCKET) {

printf("Error at socket(): %ld\笑埋n", WSAGetLastError())

WSACleanup()

return 1

}

service.sin_family = AF_INET

service.sin_addr.s_addr = inet_addr("127.0.0.1")

service.sin_port = htons(27115)

if (bind( ListenSocket,

(SOCKADDR*) &service,

sizeof(service)) == SOCKET_ERROR) {

printf("bind() failed.\盯纯n")

closesocket(ListenSocket)

WSACleanup()

return 1

}

if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {

printf("Error listening on socket.\n")

closesocket(ListenSocket)

WSACleanup()

return 1

}

argument.lock = 1

printf("Waiting for client to connect...\n")

pthread_create(&tid,NULL,timer,NULL)

while(TRUE){

argument.accpt = accept( ListenSocket, (SOCKADDR*)&client, &len )

if (argument.accpt == INVALID_SOCKET) {

printf("accept failed: %d\n", WSAGetLastError())

closesocket(ListenSocket)

WSACleanup()

return 1

} else {

printf("accept%s:%d\n",inet_ntoa(client.sin_addr),client.sin_port)

while (!argument.lock)

argument.lock = 0

// sendto(argument.accpt,sendBuf,sizeof(sendBuf),0,(SOCKADDR*)&client,len)

pthread_create(&tid,NULL,transfer,&argument)

//send(AcceptSocket,sendBuf,sizeof(sendBuf),0)

}

}

// No longer need server socket

closesocket(ListenSocket)

WSACleanup()

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12334246.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存