Python version:
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 (s Ocket.af_inet, Socket. SOCK_STREAM)
Client.connect (HOST, PORT)
Client.settimeout
Flag=true
While flag:
REVEIVED_DATA=CLIENT.RECV (1024x768)
Print (reveived_data)
If Reveived_data = = bytes ("Over", encoding= "u Tf-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_d ATA = = Bytes ("MSG2", encoding= "Utf-8"):
Client.sendall (bytes (' Msg3 ', encoding= "Utf-8")
If Reveiv Ed_data = = Bytes ("Msg4", encoding= "Utf-8"):
Client.sendall (bytes (' Msg5 ', encoding= ' utf-8 ')
Print ("Co Nnect closed ")
C:
Write sockets on Windows with Codeblocks to import sockets, import libws2_32.a and libwsock32.a in Complier
The code is as follows:
#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 ();
}
Socket Programming Python+c