Skip to content

Instantly share code, notes, and snippets.

@BenKnisley
Last active August 29, 2022 09:50
Show Gist options
  • Save BenKnisley/5647884 to your computer and use it in GitHub Desktop.
Save BenKnisley/5647884 to your computer and use it in GitHub Desktop.
Two way communication Python Server-Client pair
Simple Python Server-Client Pair With Two Way Communication
#!/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()
#!/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()
@markkuleppala
Copy link

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

@emregoenen
Copy link

Thanks for sharing your work ! I've created full-duplex TCP/IP communication between two ends using threads.

@khthana
Copy link

khthana commented Apr 19, 2022

s.send(D + '\r')

TypeError: a bytes-like object is required, not 'str'

@WaGi-Coding
Copy link

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