Last active
August 29, 2022 09:50
-
-
Save BenKnisley/5647884 to your computer and use it in GitHub Desktop.
Two way communication Python Server-Client pair
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Simple Python Server-Client Pair With Two Way Communication |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import socket, time | |
def Tcp_connect( HostIp, Port ): | |
global s | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.connect((HostIp, Port)) | |
return | |
def Tcp_Write(D): | |
s.send(D + '\r') | |
return | |
def Tcp_Read( ): | |
a = ' ' | |
b = '' | |
while a != '\r': | |
a = s.recv(1) | |
b = b + a | |
return b | |
def Tcp_Close( ): | |
s.close() | |
return | |
Tcp_connect( '127.0.0.1', 17098) | |
Tcp_Write('hi') | |
print Tcp_Read() | |
Tcp_Write('hi') | |
print Tcp_Read() | |
Tcp_Close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import socket, time | |
#things to begin with | |
def Tcp_connect( HostIp, Port ): | |
global s | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.connect((HostIp, Port)) | |
return | |
def Tcp_server_wait ( numofclientwait, port ): | |
global s2 | |
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s2.bind(('',port)) | |
s2.listen(numofclientwait) | |
def Tcp_server_next ( ): | |
global s | |
s = s2.accept()[0] | |
def Tcp_Write(D): | |
s.send(D + '\r') | |
return | |
def Tcp_Read( ): | |
a = ' ' | |
b = '' | |
while a != '\r': | |
a = s.recv(1) | |
b = b + a | |
return b | |
def Tcp_Close( ): | |
s.close() | |
return | |
Tcp_server_wait ( 5, 17098 ) | |
Tcp_server_next() | |
print Tcp_Read() | |
Tcp_Write('hi') | |
print Tcp_Read() | |
Tcp_Write('hi') | |
Tcp_Close() | |
Thanks for sharing your work ! I've created full-duplex TCP/IP communication between two ends using threads.
s.send(D + '\r')
TypeError: a bytes-like object is required, not 'str'
Thanks for sharing your work ! I've created full-duplex TCP/IP communication between two ends using threads.
can you share it? ^^
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello! Thanks for the code provided! Used it on my project as a base for communication. Made a minor change to Tcp_Read() to avoid extra \r in the end.
def Tcp_Read(): a = ' ' b = '' a = s.recv(1) while a != '\r': b = b + a a = s.recv(1) return b