mateus
mateus

Reputation: 51

client-server chat python error

I'm trying the following client and server chat program. Although I get an error whenever I try to run the server program, when the client program runs it stays on a blank screen not allowing me to type anything. I've tried running server first and running client first and I get the same results. I can't read the error from the server program because it flashes the error and closes the window. Here is my code:

server:

 #server
 import socket
 import time

 HOST = ''
 PORT = 8065
 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 s.bind((HOST,PORT))
 s.listen(1)
 conn, addr = s.accept()
 print 'Connected by', addr
 while 1:
     data = conn.recv(1024)
     if not data: break
     conn.sendall(data)
 conn.close()

client:

  #client
  import socket
  import time

  HOST = "localhost"
  PORT = 8065
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  s.connect((HOST,PORT))
  s.sendall('Helloworld')
  data = s.recv(1024)
  s.close()
  print 'Recieved', repr(data)

Upvotes: 0

Views: 366

Answers (1)

user3126264
user3126264

Reputation:

Im not an expert but I was able to make your examples work by changing the socket from datagram to stream connection, and then encoding message being sent because strings aren't supported (although this might not effect you since I think that change was made in Python 3...I'm not 100% sure).

I believe the main issue is that you're trying to listen() but SOCK_DGRAM (UDP) doesn't support listen(), you just bind and go from there, whereas SOCK_STREAM (TCP) uses connections.

If you're just trying to get the program going, use the below code, unless there is a specific reason you'd like to use SOCK_DGRAM.

The code is below:

client

#client
import socket
import time

HOST = "localhost"
PORT = 8065
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
test = 'Helloworld'
s.sendall(test.encode())
data = s.recv(1024)
s.close()
print 'Recieved', repr(data)

server

#server
import socket
import time

HOST = ''
PORT = 8065

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

Upvotes: 1

Related Questions