标签:lag 编写 cli get wsad c语言 finish oid mem
python版:
server:
def socket_loop_server_function():
HOST = ‘192.168.56.1‘
PORT = 21567
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.bind((HOST, PORT))
sk.listen(1)
while True:
sock, addr = sk.accept()
sock.sendall(b‘begin‘)
flag=True
while flag:
data=sock.recv(1024)
print("recevied:%s" % data)
if data == bytes("msg1",encoding="utf-8"):
feedback=input("please input the feedback:")
sock.send(bytes(feedback, encoding=‘utf-8‘))
if feedback == "over":
flag=False
if data == bytes("msg3",encoding="utf-8"):
feedback = input("please input the feedback:")
sock.send(bytes(feedback, encoding=‘utf-8‘))
if feedback == "over":
flag = False
if data == bytes("msg5",encoding="utf-8"):
feedback = input("please input the feedback:")
sock.send(bytes(feedback, encoding=‘utf-8‘))
if feedback == "over":
flag = False
sock.close()
break
print("connect finished")
client:
def socket_loop_customer_function():
HOST = ‘192.168.56.1‘
PORT = 21567
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
client.settimeout(10)
flag=True
while flag:
reveived_data=client.recv(1024)
print(reveived_data)
if reveived_data == bytes("over",encoding="utf-8"):
client.close()
flag=False
time.sleep(2)
if reveived_data == bytes("begin",encoding="utf-8"):
client.sendall(bytes(‘msg1‘, encoding="utf-8"))
if reveived_data == bytes("msg2",encoding="utf-8"):
client.sendall(bytes(‘msg3‘, encoding="utf-8"))
if reveived_data == bytes("msg4",encoding="utf-8"):
client.sendall(bytes(‘msg5‘, encoding="utf-8"))
print("connect closed")
c语言版:
在windows上用codeblocks编写socket需要导入socket的库,在complier中导入libws2_32.a和libwsock32.a
代码如下:
#include <winsock2.h>
#pragma comment(lib , "ws2_32.lib") #导入库
void socket_function(){
WSADATA wsd;
struct sockaddr_in dest;
char buf[400];
char sendbuf[400];
WSAStartup( MAKEWORD(2, 2), &wsd); #加载库
SOCKET socketfd= socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
dest.sin_family=AF_INET;
dest.sin_port=htons(21567);
dest.sin_addr.s_addr=inet_addr("192.168.56.1");
memset(&(dest.sin_zero),0,sizeof(struct sockaddr_in));
if(connect(socketfd,(struct sockaddr*)&dest,sizeof(struct sockaddr_in)) == -1){
printf("failed %d\n",WSAGetLastError());
}
while(1){
printf("connect success\n");
recv(socketfd,buf,1024,0);
printf("buf=%s\n",buf);
// strcpy(sendbuf,"msg1");
printf("please input the msg:\n");
scanf("%s",sendbuf);
send(socketfd,sendbuf,strlen(sendbuf),0);
}
closesocket(socketfd);
WSACleanup();
}
标签:lag 编写 cli get wsad c语言 finish oid mem
原文地址:https://www.cnblogs.com/zhanghongfeng/p/9324364.html