Skip to content

Instantly share code, notes, and snippets.

@mako34
Created October 23, 2013 05:28
Show Gist options
  • Save mako34/7113011 to your computer and use it in GitHub Desktop.
Save mako34/7113011 to your computer and use it in GitHub Desktop.
Python simple chat test, server and client
#server
# TCP Server Code
#host="127.0.0.1" # Set the server address to variable host
host="127.168.2.75" # Set the server address to variable host
port=4446 # Sets the variable port to 4444
from socket import * # Imports socket module
s=socket(AF_INET, SOCK_STREAM)
s.bind((host,port)) # Binds the socket. Note that the input to
# the bind function is a tuple
s.listen(1) # Sets socket to listening state with a queue
# of 1 connection
print "Listening for connections.. "
q,addr=s.accept() # Accepts incoming request from client and returns
# socket and address to variables q and addr
data=raw_input("Enter data to be send: ") # Data to be send is stored in variable data from
# user
q.send(data) # Sends data to client
s.close()
# End of code
#Client
# TCP Client Code
#host="127.0.0.1" # Set the server address to variable host
host = "127.168.2.75"
port=4446 # Sets the variable port to 4444
from socket import * # Imports socket module
s=socket(AF_INET, SOCK_STREAM) # Creates a socket
s.connect((host,port)) # Connect to server address
msg=s.recv(1024) # Receives data upto 1024 bytes and stores in variables msg
print ("Message from server : " + msg.strip().decode('ascii'))
s.close() # Closes the socket
# End of code
@mhsharifi96
Copy link

tnx

@arcilli
Copy link

arcilli commented May 29, 2018

Little bug in Python 2.7

 s.connect((host,port))          # Connect to server address
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 111] Connection refused

@DAEXDO3240
Copy link

gives me this error to me, at the point where I have to insert:

Listening for connections..
Enter data to be send: cacca.txt
Traceback (most recent call last):
File "C:/Users/Davide/Desktop/server chat.py", line 26, in
q.send(data) # Sends data to client
TypeError: a bytes-like object is required, not 'int'

@denny0754
Copy link

@DAEXDO3240 you need to encode the data: q.send(data.encode('utf-8')
If you were trying to send a file('cacca.txt') it'll not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment