Skip to content

Instantly share code, notes, and snippets.

@AliYmn
Created March 5, 2017 01:15
Show Gist options
  • Save AliYmn/080dcd9990ce812ef58fff5dc606538a to your computer and use it in GitHub Desktop.
Save AliYmn/080dcd9990ce812ef58fff5dc606538a to your computer and use it in GitHub Desktop.
Python3x socket example
import socket
import sys
def get_constants(prefix):
"""Create a dictionary mapping socket module constants to their names."""
return dict((getattr(socket, n), n)
for n in dir(socket)
if n.startswith(prefix)
)
families = get_constants('AF_')
types = get_constants('SOCK_')
protocols = get_constants('IPPROTO_')
# Create a TCP/IP socket
sock = socket.create_connection(('localhost', 10000))
try:
# Send data
message = 'Merhaba Dünya'
print('Gönderilen Veri : "%s"' % message)
sock.sendall(message.encode('utf-8'))
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print('Geri Gelen Veri : "%s"' % data)
finally:
print('Socket kapandı!')
sock.close()
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the address given on the command line
server_address = ('localhost', 10000)
sock.bind(server_address)
print('Server çalışmaya başladı %s port bilgisi : %s' % sock.getsockname())
sock.listen(1)
while True:
connection, client_address = sock.accept()
try:
print('Baglanan Kullanici Baglanti Adresi : ', client_address)
while True:
data = connection.recv(16)
if data:
connection.sendall(data)
print('Başarıyla şunu yolladı : "%s"' % data)
else:
connection.close()
break
finally:
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment