Socket programming

Dan Stromberg drsalists at gmail.com
Sat Jan 3 12:16:57 EST 2015


On Sat, Jan 3, 2015 at 3:43 AM, pramod gowda <pramod.sp78 at gmail.com> wrote:
> Hi i am learning socket programming,

This "works" on Linux Mint 17.1.

Server:
#!/usr/local/cpython-3.4/bin/python

import socket

server_socket = socket.socket()
#server_name = '192.168.2.2'
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_name = 'localhost'
server_port = 8080
server_socket.bind((server_name, server_port))
server_socket.listen(1)

while True:
    print("hello")
    c,address = server_socket.accept()
    print("we got connection from:",address)
    c.send(b"hello,hw ru")
    c.close()


client:
#!/usr/local/cpython-3.4/bin/python

import socket

client_socket = socket.socket()
#server_address='192.168.2.2'
server_address = 'localhost'
server_port = 8080
print("hello")
client_socket.connect((server_address,server_port))
print("hello")
data=client_socket.recv(1024)
print(data)
client_socket.close()


But note that if you send 10 bytes into a socket, it could be received
as two chunks of 5, or other strangeness. So you should frame your
data somehow - adding crlf to the end of your send's is one simple
way.  There are multiple ways of dealing with this.  Here's one:
http://stromberg.dnsalias.org/~strombrg/bufsock.html with links to
others.



More information about the Python-list mailing list