简体   繁体   中英

Simple TCP EchoServer in Python

I found this script of TCP server which "echoes" back the data to the client.

#!/usr/bin/env python 

import socket

host = ''
port = 50000
backlog = 5 
size = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host,port)) 
s.listen(backlog) 
while 1: 
    client, address = s.accept() 
    data = client.recv(size) 
    if data: 
        client.send(data) 
    client.close()

I'm trying to test & understand it before I will be able to do something on my own and modify, but I'm having some problems. When I'm trying to run the .py script I get the following error in my Terminal (using Ubuntu 14.04 LTS)

> Traceback (most recent call last):
  File "echo.py", line 14, in <module>
    s.bind((host,port))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

My Python version is 2.7.6

is there something wrong with the code or I'm doing something wrong?

UPDATE:

it gets worse, any script I run with bind(host, port) gives me the same error.

any help would be appreciated

Perhaps you accidentally ran the EchoServer twice in different windows? You can only bind one receiver to a port/address combination.

Seems like there is some other application running on those ports.

Can you try checking if there are any other app listening on same port using:

netstat -ntlpu | grep 50000

To bind a server it's a little confusing but you have to use a tuple. The correct way is server.bind((host, port))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM