G
G
George1232019-02-04 21:17:16
Java
George123, 2019-02-04 21:17:16

Why doesn't this code work and can't be killed with ctrl+z?

I took this code from one tutorial, tried to run it, but it still does not work safely.

import socket, time

host = socket.gethostbyname(socket.gethostname())# получает имя машины, на которой запущен питон и конвертирует в строку IpV4
port = 9873

clients = []

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#создание самого сокета 
s.bind((host,port))#привязывает сокет к данному адресу

quit = False
print("[ Server Started ]")

while not quit:
  try:
    data, addr = s.recvfrom(1024)#получает инфу с сокета; возвращает список из инфы в 1024 байт и адреса 

    if addr not in clients:
      clients.append(addr)

    itsatime = time.strftime("%Y-%m-%d-%H.%M.%S", time.localtime())

    print("["+addr[0]+"]=["+str(addr[1])+"]=["+itsatime+"]/",end="")
    print(data.decode("utf-8"))

    for client in clients:
      if addr != client:
        s.sendto(data,client)#отправка сообщения
  except:	
    print("\n[ Server Stopped ]")
    quit = True
    
s.close()

that was the server and this is the client
import socket, threading, time



shutdown = False
join = False

def receving (name, sock):
  while not shutdown:
    try:
      while True:
        data, addr = sock.recvfrom(1024)
        print(data.decode("utf-8"))



        time.sleep(0.2)
    except:
      pass
host = socket.gethostbyname(socket.gethostname())
port = 0

server = ("192.168.0.101",9873)

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)

alias = input("Name: ")

rT = threading.Thread(target = receving, args = ("RecvThread",s))
rT.start()

while shutdown == False:
  if join == False:
    s.sendto(("["+alias + "] => join chat ").encode("utf-8"),server)
    join = True
  else:
    try:
      message = input()

      if message != "":
        s.sendto(("["+alias + "] :: "+message).encode("utf-8"),server)
      
      time.sleep(0.2)
    except:
      s.sendto(("["+alias + "] <= left chat ").encode("utf-8"),server)
      shutdown = True

rT.join()
s.close()

When I launch this chat client and enter a name, it crashes and gives "OSError: [WinError 10051] An attempt was made to perform an operation on a socket while the network is down". How can it be cured?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
maxt888, 2016-07-07
@maxt888

Try updating IDEA

G
Garik_Shuster, 2016-07-07
@Garik_Shuster

IMHO
If IDEA is licensed, either something is wrong with the JAVA config in the system, or something is wrong with Windows.
How long has it been? If you create a new project, is it the same?

Z
Zanak, 2019-02-04
@Georgy123

you have a jamb in the server code, you have lost listen and accept.
Try reading this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question