Socket Program Python

Socket Program Python

By : Lyle_66
Date : November 18 2020, 03:01 PM
hop of those help? A couple of things I had issues with until I could get it working: 1. notice when you take input use raw_input, otherwise it crashed for me. 2.where you thought there was an issue in the server there really was one. You accidentally close connection and then send once the game is lost 3. in the client you have loseGame = loseGame.encode('utf-8') instead of loseGame = loseGameInBytes.encode('utf-8') 4. I change the print statements to print(str(x) + " "), because yours gave me issues
This is the code after I fixed it. Notice I changed and added breaks in the server that aren't necessary and they will cause the server to close at the end of a single game.
code :
import sys

# Import socket library
from socket import *

if sys.argv.__len__() != 2:
    serverPort = 5895
# Get port number from command line
    serverPort = int(sys.argv[1])

# Choose SOCK_STREAM, which is TCP
# This is a welcome socket
serverSocket = socket(AF_INET, SOCK_STREAM)

serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

# Start listening on specified port
serverSocket.bind(('', serverPort))

# Listener begins listening

print("The server is ready to receive")

#Set secret word
word = 'respecttheplatypus'
linesForString = ''     
#Prints out number of letters
for x in word:
    linesForString += '_'

newWord = 'respecttheplatypus'

# Wait for connection and create a new socket
# It blocks here waiting for connection
connectionSocket, addr = serverSocket.accept()
win = ' '
#Sends lines of words
linesInBytes = linesForString.encode('utf-8')

lose = 0
while 1:

    l = list(word)
    list2 = list(linesForString)

    win = False 

    while 1:

        while win == False:
            losee = 0
            # Receives Letter
            letter = connectionSocket.recv(1024)
            letterString = letter.decode('utf-8')

            for x in range(len(list2)): 
                if(list2[x] == '_'):
                    if(letterString == l[x]):
                        list2[x] = letterString     

            for x in range(len(word)):
                if(letterString == word[x]):
                    losee = -1
            if (losee != -1):
                lose += 1

            newWord = "".join(list2)

            #Sends newWord
            newWordInBytes = newWord.encode('utf-8')
            connectionSocket.send(newWordInBytes, lose)

            if(newWord == 'respecttheplatypus'):
                win = True
                winGame = 'You have won the game'
                winGameInBytes = winGame.encode('utf-8')

                if(lose == 7):
                    loseGame = 'true'
                    loseGameInBytes = loseGame.encode('utf-8')
                    loseGame = 'false'
                    loseGameInBytes = loseGame.encode('utf-8')
import sys

# Import socket library
from socket import *

if sys.argv.__len__() != 3:
    serverName = 'localhost'
    serverPort = 5895
# Get from command line
    serverName = sys.argv[1]
    serverPort = int(sys.argv[2])

# Choose SOCK_STREAM, which is TCP
clientSocket = socket(AF_INET, SOCK_STREAM)

# Connect to server using hostname/IP and port
clientSocket.connect((serverName, serverPort))

#Recieves lines of words
linesInBytes = clientSocket.recv(1024)
lines = linesInBytes.decode('utf-8') 
for x in lines:
    print(str(x) + " "),

while 1:

    # Get letter from user
    letter = raw_input('Guess a letter: ')

    # Sends letter
    letterBytes = letter.encode('utf-8')

    #Recieves newWord
    newWordInBytes = clientSocket.recv(len(linesInBytes))
    newWord = newWordInBytes.decode('utf-8')

    for x in newWord:
        print(str(x) + " "),
    print(" ")  

    if(newWord == 'respecttheplatypus'):
        winGameInBytes = clientSocket.recv(1024)
        winGame = winGameInBytes.decode('utf-8')

    loseGame = " "
    loseGameInBytes = clientSocket.recv(1024)   
    loseGame = loseGameInBytes.encode('utf-8')

    print("lose game is" + str(loseGame))
    if(loseGame == "true"):
        print('You have lost the game!')

Share : facebook icon twitter icon
Socket program Python vs C++ (Winsock)

Socket program Python vs C++ (Winsock)

By : Ketan Patel
Date : March 29 2020, 07:55 AM
I hope this helps . Per the docs, sendto returns a number that's >0 (number of bytes sent) for success, <0 for failure, and in the latter case you use WSAGetLastError for more information. So try saving the sendto result, printing it (as well as the size of the data you're trying to send), and in case of error print the last-error code too. What do you see then?
Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket

Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket

By : user2363203
Date : March 29 2020, 07:55 AM
I wish this help you sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Should do the trick.
Convert C socket program to python

Convert C socket program to python

By : DisplayName=
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You didn't convert the C code to Python right. In C, a UDP socket was created by
code :
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    n=recvfrom(sid,buffer,1023,0,(struct sockaddr*)&caddr,&clen);
        buffer, caddr = s.recvfrom(1023)
Python socket , why would the program blocked?

Python socket , why would the program blocked?

By : Nadeem Delhiwala
Date : March 29 2020, 07:55 AM
seems to work fine Your client hanging is the expected behaviour, as no one initiates a socket shutdown. socket.recv() blocks until data is available. It does not return None if your socket is alive but there is no data to be read.
If your intention on the server side is to receive a message, then do something, return a response and finally close connection, this works:
code :
def tr(sock, addr):
    while True:
        data = sock.recv(1024)
        if data:
            sock.send(b'get it')
            break #never gets here
python socket (TCP) program does not end

python socket (TCP) program does not end

By : Felix Wortmann
Date : March 29 2020, 07:55 AM
will help you I have solved all problems with the last revision. It works very well. I'm glad I solved it on my own, even if nobody helped me. When we run as a client only if the data does not exist in the database, it is also added easily after that.
code :
import socket
import sys
import traceback
from threading import Thread
import Veri_Tabanı

bağlanan =0
sayac =0
bağlanan_sayaç_liste = [-1]

def main():
    while True:
        Haberleşme Uygulaması (TCP)

        Client mi yoksa Server mi?:
        1- Client
        2- Server

        'q' ile çıkış yapınız.
        seçim=input("Seçim Yapınız: ")
        if seçim == "1":
        elif seçim == "2":
        elif seçim == "q":
            print("Doğru Seçim Yapınız.")

def baslat_server():
    global bağlanan
    global sayac
    global bağlanan_sayaç_liste
    global sockt
    global socket

    ip = ""
    port = 4444
    sockt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sockt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print("Server Açıldı")

        sockt.bind((ip, port))
        print("Bağlantı Hatası: " + str(sys.exc_info()))
    while True:
            bağlantı, adres = sockt.accept()
        except OSError:
        gelen_ip, gelen_port = str(adres[0]), str(adres[1])         
        print("Bağlanan: {}:{} ".format(gelen_ip,gelen_port))   
        bağlanan += 1
            Thread(target=takıl_client, args=(bağlantı, gelen_ip, gelen_port)).start()
            print(sockt, "Client (%s, %s) Kapalı" % adres)

def takıl_client(bağlantı, gelen_ip, gelen_port, max_buffer_size = 5120):
    global bağlanan
    global sayac
    global bağlanan_sayaç_liste
    global sockt
    global socket

    verisay= 0
    acikmi = True

    while acikmi:
        client_giris = beklenen_giris(bağlantı, max_buffer_size)
        veritab = []
        if "Cikis()" in client_giris:
            print("Client çıkmak istiyor.")
            bağlanan -= 1
            sayac += 1   
            print("Bağlantı {}:{} Kapatıldı.".format(gelen_ip, gelen_port))
            acikmi = False

            if bağlanan == 0 and sayac == (int(bağlanan_sayaç_liste[(len(bağlanan_sayaç_liste))-1])):
                print("Server Kapatıldı")

            print("İşlem Sonucu: {}".format(client_giris))
            al = client_giris
            gon = gonderilen = input("Gönderilecek Yazınız: ")
            verisay +=1
            veritab = [verisay,gelen_ip,"Server",gon,al]

def beklenen_giris(bağlantı, max_buffer_size):
    client_giris = bağlantı.recv(max_buffer_size)
    client_giris_boyu = sys.getsizeof(client_giris)

    if client_giris_boyu > max_buffer_size:
        print("Giriş boyutu beklenenden büyük {}".format(client_giris_boyu))

    sifrele_giris = client_giris.decode("utf-8").rstrip()
    sonuc = islem_giris(sifrele_giris)
    return sonuc

def client():

    client = socket.socket()
    client.connect((hedef_adres, hedef_port))
    print ("q ile çıkabilirsiniz")
    gönderilen = input("Gönderilecek veri yazın:")
    if gönderilen != 'q':
        cevap = client.recv(1024).decode('utf-8')
        print('Gelen Mesaj: ' + cevap)

def islem_giris(giris_metin):
    print("Clientten işlem girişi Bekleniyor")
    return "" + str(giris_metin)

if __name__ == "__main__":
import sqlite3

vertab= sqlite3.connect("Veriler.db", check_same_thread=False)

def veri_tablosu():
    imleç.execute("CREATE TABLE IF NOT EXISTS veri_tab (Sira INT,Adres TEXT, Fonksiyon TEXT, Gonderilen TEXT, Gelen TEXT)")


def deger_ekle(sıra,ip_adres,fonksiyon,gönderilen,alınan):
    imleç.execute("INSERT INTO veri_tab (Sira,Adres,Fonksiyon,Gonderilen,Gelen) VALUES(?,?,?,?,?)",(sıra,ip_adres,fonksiyon,gönderilen,alınan))

Related Posts Related Posts :
  • How to use an API that requires user's entry (Sentiment Analysis)
  • Django first app
  • Why is this regex code not working
  • Beautifulsoup - findAll not finding string when link is also in container
  • Python: any() to check if attribute in List of Objects matches a list
  • How do I "enrich" every record in a Pandas dataframe with an hour column?
  • Failing to open an Excel file with Python
  • Python function to modify string
  • Pandas DataFrame seems not to have "factorize" method
  • Row column operations in CSV
  • How to decrypt RSA encrypted file (via PHP and OpenSSL) with pyopenssl?
  • How can we use pandas to generate min, max, mean, median, ...as new columns for the dataframe?
  • Cython: creating an array throws "not allowed in a constant expression"
  • Different thing is shown in html
  • sublimetext3 event for program exit
  • Join contigous tokens if the token includes "@" char
  • transparent background in gif using Python Imageio
  • Enable autologin into flask app using active directory
  • Make a NxN array of 1x3 arrays of random numbers (python)
  • django how to use Max and Count on the same field in back-to-back annotations
  • Using the OR operator seems to only take the first of two conditions when used with np.where filter
  • Elegant Dataframe Operations in Pandas
  • Change metadata of pdf file with pypdf2
  • How can I animate a set of points with matplotlib?
  • error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
  • OpenStack KeyStone SSL Exception When Creating an Instance of KeyStone
  • pyspark: The system cannot find the path specified
  • How can I set path to load data from CSV file into PostgreSQL database in Docker container?
  • Summation in python dictionary
  • DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
  • Error with Padlen in signal.filtfilt in Python
  • Abstract matrix multiplication with variables
  • Reading binary data on bit level
  • How to replace multiple instances of a sub strings in a string using a for loop (in a function)?
  • py2neo cypher create several relations to central node in for loop
  • [python-3]TypeError: must be str, not int
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org