用c语言写个 socket tcp 的
发布网友
发布时间:2022-04-24 20:15
我来回答
共1个回答
热心网友
时间:2022-04-07 09:33
#include <winsock2.h>
#include <stdio.h>
#include <pthread.h>
#pragma comment(lib,"ws2_32.lib")
typedef struct{
SOCKET a*t;
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->a*t,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=2;WHAT=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.a*t = accept( ListenSocket, (SOCKADDR*)&client, &len );
if (argument.a*t == 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.a*t,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;
}
发送数据格式按需求。可以发送字符串,也可以发送结构体。如果发送结构体的话,要注意序列化和反序列化。程序例子是服务器对每个客户端的connect动作起一个线程去交互。还有一个线程是定时器。
追问我想些一个简单的计算器 就是客户端输入两个数字,然后服务器返回 都是int型的 加减乘除。这种情况应该怎么弄啊