Created
October 23, 2013 05:28
-
-
Save mako34/7113011 to your computer and use it in GitHub Desktop.
Python simple chat test, server and client
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
#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 |
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'
@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
Little bug in Python 2.7