NameError: global name 'Carnage' is not defined - import

I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined

The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.

Related

Discord bot executes but doesn't function when testing in discord server

I've adjusted the main file and added a prefix "?" to my commands
import discord
from discord.ext import commands
import os
import asyncio
client = commands.Bot(command_prefix="?", intents = discord.Intents.all())
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
async def main():
async with client:
await load()
await client.start(TOKEN)
asyncio.run(main())
and added a simple ping command to test if the bot was working in discord. unfortunately all the commands except for ping does not work
import discord
from discord.ext import commands
from pymongo import MongoClient
bot_channel = BOTCHANNELID
talk_channels = [TALKCHANNELID]
level = ["test1", "test2", "test3"]
levelnum = [2,4,6]
cluster = MongoClient("MONGODBCODE")
levelling = cluster["NAME"]["NAME2"]
class levelsys(commands.Cog):
def __init__(self,client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Ready!")
#commands.Cog.listener()
async def on_message(self, message):
if message.channel.id in talk_channels:
stats = levelling.find_one({"id" : message.author.id})
if not message.author.bot:
if stats is None:
newuser = {"id" : message.author.id, "xp" : 1}
levelling.insert_one(newuser)
else:
xp = stats["xp"] + 5
levelling.update_one({"id":message.author.id}, {"$set":{"xp":xp}})
lvl = 0
while True:
if xp < ((50*(lvl**2))+(50*(lvl-1))):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
if xp == 0:
await message.channel.send(f"gz {message.author.mention} ! you lvled up to **level: {lvl}**")
for i in range(len(level)):
if lvl == levelnum[i]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{message.author.mention} you have gotten role **{level[i]}**")
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
#commands.command()
async def rank(self, ctx):
if ctx.channel.id == bot_channel:
stats = levelling.find_one({"id" : ctx.author.id})
if stats is None:
embed = discord.Embed(description="you haven't been studying lil bro")
await ctx.channel.send(embed=embed)
else:
xp = stats["xp"]
lvl = 0
rank = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
boxes = int((xp/(200*((1/2) * lvl)))*20)
rankings = levelling.find().sort("xp",-1)
for x in rankings:
rank += 1
if stats["id"] == x["id"]:
break
embed = discord.Embed(title="{}'s level stats".format(ctx.author.name))
embed.add_field(name="Name", value=ctx.author.mention, inline=True)
embed.add_field(name="XP", value=f"{xp}/{int(200*((1/2)*lvl))}", inline=True)
embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Progress Bar [lvl]", value=boxes * ":blue_square:" + (20-boxes) * ":white_large_squares:", inline = False)
embed.add_field(name='Level', value=f'{lvl}', inline=True)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
#commands.command()
async def dashboard(self, ctx):
if (ctx.channel.id == bot_channel):
rankings = levelling.find().sort("xp",-1)
i = 1
embed = discord.Embed(title="Rankings:")
for x in rankings:
try:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline=False)
i += 1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
#commands.command()
async def ping(self, ctx):
bot_latency = round(self.client.latency * 1000)
await ctx.send(f"Your ping is {bot_latency} ms !.")
async def setup(client):
await client.add_cog(levelsys(client))
I'm not too sure how I would go about fixing all the other commands to get them working. All help is much appreciated !

bypass 'google before you continue' pop-up

My code:
import pandas
import requests
from bs4 import BeautifulSoup
from pywebio.input import *
from pywebio.output import *
from time import sleep
from pywebio import start_server
print("News web application successfully started!")
def app():
request = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")
content = BeautifulSoup(request.content, 'html.parser')
find = content.find('div', class_='ajwQHc BL5WZb')
#open('test.html', 'w').write(findstr.find)
h3 = find.find_all('h3')
time = find.find_all('time')
link = find.find_all('article')#.find_all('a').get('href').replace('.', '')
result = []
#print('https://news.google.com' + link)
#put_html('<table border="1" width="100%" cellpadding="5">')
source = find.find_all('a', {'data-n-tid' : '9'})
time = find.find_all('time')
textoutput = []
textoutput1 = []
textoutput2 = []
takeoutput3 = []
#writer = open('news.csv', 'w')
#writer1 = csv.writer(writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for text in h3:
a1 = text.text
textoutput.append(a1)
for text2 in source:
a3 = text2.text
textoutput1.append(a3)
for text1 in time:
a5 = text1.text
textoutput2.append(a5)
#for result in link:
# alinks = result.find_all('a')
# alinks1 = []
# for alinks1 in alinks:
# alinks2 = alinks1.get('href')
# alinksreplace = str(alinks2)
# alinksreplace1 = alinksreplace.replace(".", "")
# alinksreplace2 = alinksreplace1.replace("None", "")
#
# if (alinksreplace2 != ''):
# if "publications" not in alinksreplace2:
# a = "https://news.google.com" + alinksreplace2
# takeoutput3.append(a)
pandas.set_option('display.max_colwidth', None)
frame = {'Title':textoutput, 'Time':textoutput2, 'Source' : textoutput1}
frame1 = pandas.DataFrame(frame)
#frame2 = {'Link' : takeoutput3}
#frame3 = pandas.DataFrame(frame2)
frametostring = frame1.to_string(index=False)
#frametostring1 = frame3.to_string(index=False)
#print(frametostring)
put_code(frametostring)
#put_code(frametostring1)
#writer1.writerow([textoutput, textoutput1, textoutput2])
start_server(app, 82)
it worked fine but today Google update something and now it don't start. And it's because Google add before you continue pop-up. How I can bypass this so my script continue to work?
If it was Selenium I've just clicked the button but here I don't know what to do
Thanks you helping!

How to get filepath from droped file with pyqt5?

I want to get path of the file dropped on QLabel. So I code like this, but label doesn't accept the file. What is the problem..?
Here is my code. So long code sorry and thank you!
import random
import sys
import pygame
import time
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDesktopWidget
class Example(QWidget):
size=100
imgNum=0
frameCount=4
isXmin = False
isXmax = False
isYmin = False
isYmax = False
isLeft= True
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
sizeObject = QDesktopWidget().screenGeometry()
# print(" Screen size : " + str(sizeObject.height()) + "x" + str(sizeObject.width()))
self.xMax=sizeObject.width()-10
self.yMax=sizeObject.height()-10
print(self.xMax)
print(self.yMax)
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setStyleSheet("background-color:transparent;")
self.setGeometry(100, 100, 100, 100)
self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
self.setAcceptDrops(True)
self.label=QLabel(self)
self.label.setAcceptDrops(True)
self.pixmaps=[QPixmap('left.png'),QPixmap('stand.png'),QPixmap('right.png'),QPixmap('stand.png'),QPixmap('leftR.png'),QPixmap('standR.png'),QPixmap('rightR.png'),QPixmap('standR.png')]
for x in range(len(self.pixmaps)):
self.pixmaps[x]=self.pixmaps[x].scaled(self.size,self.size,Qt.KeepAspectRatio)
self.resize(self.pixmaps[2].width(),self.pixmaps[2].height())
self.label.setPixmap(self.pixmaps[len(self.pixmaps)-1])
self.changeTimer=QTimer(self)
self.changeTimer.timeout.connect(self.changeFoot)
self.moveTimer=QTimer(self)
self.moveTimer.timeout.connect(self.moving)
self.setAcceptDrops(True)
pygame.init()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
self.show()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
def moving(self):
if self.distance == 0:
print(self.distance)
print(self.x(),"x",self.y())
self.label.setPixmap(self.pixmaps[1])
self.moveTimer.stop()
self.changeTimer.stop()
time.sleep(3)
self.setMovement()
return 0
else:
self.move(self.x()+self.direct[0],self.y()+self.direct[1])
self.distance-=1
if self.x()<=-10 :
self.distance=0
print("xm")
self.isXmin = True
if self.y()<=-10 :
self.distance=0
print("ym")
self.isYmin = True
if self.x()>=self.xMax:
self.distance=0
print("xM")
self.isXmax=True
if self.y()>=self.yMax :
self.distance=0
print("yM")
self.isYmax=True
def setMovement(self):
self.direct=[0,0]
while(self.direct[0]==0 and self.direct[1]==0):
self.direct=[random.randint(-1,1),random.randint(-1,1)]
if self.isXmax:
self.direct[0]=-1
if self.isXmin:
self.direct[0]=1
if self.isYmin:
self.direct[1]=1
if self.isYmax:
self.direct[1]=-1
if self.direct[0]== -1:
self.isLeft=True
self.imgNum=0
elif self.direct[0]== 1:
self.isLeft=False
self.imgNum=4
self.isXmax = False
self.isXmin = False
self.isYmin = False
self.isYmax = False
# if direct[0]*direct[1]==0 : self.delta = QPoint(dX*direct[0],dY*direct[1])
# else: self.delta=QPoint(direct[0]*(dX**(1/2)),direct[1]*(dY**1/2))
self.distance=random.randint(200,400)
self.changeTimer.start(300)
self.moveTimer.start(30)
def changeFoot(self):
self.label.setPixmap(self.pixmaps[self.imgNum])
if self.isLeft:
if self.imgNum<self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=0
else:
if self.imgNum<2*self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=self.frameCount
def mousePressEvent(self, QMouseEvent):
self.setMovement()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Escape:
sys.exit()
# if QKeyEvent.key() == Qt.Key_G:
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
i set AcceptDrops(True)
self.setAcceptDrops(True)
and code about get filepath ▼
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
Try to loop through event.mimeData().urls()
for url in event.mimeData().urls():
self.path = url.toLocalFile()

Connecting methods to custom QListView widgets - PyQt5 & postgreSQL

I have a simple Qt application which adds and lists records retrieved from a postgresql db in a QListView using custom widgets. I am having some difficulty setting up a pushbutton (bottom left corner of each list item instance) which will effectively use the record primary key (of the instance) to delete the record from the db
from PyQt5 import QtCore, QtWidgets
import psycopg2
import sys
import dbAPP_GUI
import listItem_GUI
class dbAPP(QtWidgets.QMainWindow, dbAPP_GUI.Ui_MainWindow):
def __init__(self, parent=None):
super(dbAPP, self).__init__(parent)
self.setupUi(self)
self.conn = psycopg2.connect(database="Name", user="anthony#primeinstr.co.za"
, password="14581458", host="127.0.0.1")
self.ListItemLine = listItem()
# ==============
# CONNECTIONS
# ==============
self.btn_save.clicked.connect(self.writeData)
self.tabWidget.currentChanged.connect(self.fetchData)
self.btn_go.clicked.connect(self.searchData)
# =============
# METHODS
# =============
def writeData(self):
name = self.name_lineEdit.text()
surn = self.surname_lineEdit.text()
age = self.age_lineEdit.text()
address = self.address_lineEdit.text()
if len(name) > 0:
c = self.conn.cursor()
c.execute(" INSERT INTO info (name, surname, age, address)"
"VALUES (%s, %s, %s, %s)", (name, surn, age, address))
self.conn.commit()
QtWidgets.QMessageBox.information(self, "Notice", "Information was successfully written to database")
self.name_lineEdit.clear()
self.surname_lineEdit.clear()
self.age_lineEdit.clear()
self.address_lineEdit.clear()
else:
QtWidgets.QMessageBox.warning(self, "Warning", "The name field is empty, please enter a value")
def fetchData(self):
self.listWidget.clear()
lineNo = 0
c = self.conn.cursor()
c.execute("SELECT * FROM info;")
listing = c.fetchall()
for i in listing:
name = (str(i[:1]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
surn = (str(i[1:2]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
age = (str(i[2:3]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
address = (str(i[3:4]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
ID = (str(i[4:5]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
nameSurn = name + " " + surn
lineNo += 1
label = listItem()
label.num_label.setText(str(lineNo))
label.nameSurn_label.setText(nameSurn)
label.age_label.setText(age)
label.address_label.setText(address)
label.id_label.setText(ID)
x = QtWidgets.QListWidgetItem()
x.setSizeHint(QtCore.QSize(280, 60))
self.listWidget.addItem(x)
self.listWidget.setItemWidget(x, label)
label.show()
def searchData(self):
self.listWidget_2.clear()
lineNo = 0
c = self.conn.cursor()
c.execute("SELECT * FROM info;")
results = c.fetchall()
for i in results:
name = (str(i[:1]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
surn = (str(i[1:2]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
age = (str(i[2:3]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
address = (str(i[3:4]).replace("(", "").replace(")", "").replace("'", "").replace(",", ""))
nameSurn = name + " " + surn
if str(self.search_lineEdit.text()).lower() == name.lower()\
or str(self.search_lineEdit.text()).lower() == surn.lower()\
or str(self.search_lineEdit.text()).lower() == address.lower():
lineNo += 1
label = listItem()
label.num_label.setText(str(lineNo))
label.nameSurn_label.setText(nameSurn)
label.age_label.setText(age)
label.address_label.setText(address)
x = QtWidgets.QListWidgetItem()
x.setSizeHint(QtCore.QSize(280, 60))
self.listWidget_2.addItem(x)
self.listWidget_2.setItemWidget(x, label)
label.show()
# ======================================================================================================================
class listItem(QtWidgets.QWidget, listItem_GUI.Ui_lineItem):
def __init__(self, parent=None):
super(listItem, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setupUi(self)
self.btn_del.clicked.connect(self.delData)
def delData(self):
ID = self.id_label.text()
print(ID)
c = psycopg2._ext.connection.cursor()
c.execute("DELETE FROM info WHERE id=(%s)", (ID))
# ======================================================================================================================
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
main = dbAPP()
main.show()
List = listItem()
List.hide()
sys.exit(app.exec_())
Currently it's failing because the cursor object in the method "DelData" requires an argument. If however this is the correct way of doing this, I can honestly not say. So if anyone has any better suggestions, that could also work. I'm just trying to find my feet with PyQt, postgreSQL and Python :)
The second argument to execute is a sequence or mapping. But you are effectively passing a string, because a tuple is primarily defined by commas, not parentheses.
So you should either do this:
c.execute("DELETE FROM info WHERE id=%s", (ID,)) # tuple
or this:
c.execute("DELETE FROM info WHERE id=%s", [ID]) # list
or this:
c.execute("DELETE FROM info WHERE id=%(ID)s", {'ID': ID}) # dict

server doesn't send data to clients

I have this piece of code for server to handle clients. it properly receive data but when i want to send received data to clients nothing happens.
server
import socket
from _thread import *
class GameServer:
def __init__(self):
# Game parameters
board = [None] * 9
turn = 1
# TCP parameters specifying
self.tcp_ip = socket.gethostname()
self.tcp_port = 9999
self.buffer_size = 2048
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.s.bind((self.tcp_ip, self.tcp_port))
except:
print("socket error, Please try again! ")
self.s.listen(5)
print('Waiting for a connection...')
def messaging(self, conn):
while True:
data = conn.recv(self.buffer_size)
if not data:
break
print("This data from client:", data)
conn.send(data)
def thread_run(self):
while True:
conn, addr = self.s.accept()
print('connected to: ' + addr[0] + " : " + str(addr[1]))
start_new_thread(self.messaging, (conn,))
def main():
gameserver = GameServer()
gameserver.thread_run()
if __name__ == '__main__':
main()
'
I want to if data received completely send to clients by retrieve the address of sender and send it to other clients by means of conn.send() but seems there is no way to do this with 'send()' method.
The piece of client side code
'
def receive_parser(self):
global turn
rcv_data = self.s.recv(4096)
rcv_data.decode()
if rcv_data[:2] == 'c2':
message = rcv_data[2:]
if message[:3] == 'trn':
temp = message[3]
if temp == 2:
turn = -1
elif temp ==1:
turn = 1
elif message[:3] == 'num':
self.set_text(message[3])
elif message[:3] == 'txt':
self.plainTextEdit_4.appendPlainText('client1: ' + message[3:])
else:
print(rcv_data)
'
the receiver method does not receive any data.
I modified your code a little(as I have python 2.7) and conn.send() seems to work fine. You can also try conn.sendall(). Here is the code I ran:
Server code:
import socket
from thread import *
class GameServer:
def __init__(self):
# Game parameters
board = [None] * 9
turn = 1
# TCP parameters specifying
self.tcp_ip = "127.0.0.1"#socket.gethostname()
self.tcp_port = 9999
self.buffer_size = 2048
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.s.bind((self.tcp_ip, self.tcp_port))
except:
print("socket error, Please try again! ")
self.s.listen(5)
print('Waiting for a connection...')
def messaging(self, conn):
while True:
data = conn.recv(self.buffer_size)
if not data:
break
print("This data from client:", data)
conn.send(data)
def thread_run(self):
while True:
conn, addr = self.s.accept()
print('connected to: ' + addr[0] + " : " + str(addr[1]))
start_new_thread(self.messaging, (conn,))
def main():
gameserver = GameServer()
gameserver.thread_run()
main()
Client code:
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9999))
def receive_parser():
#global turn
s.sendall("hello world")
rcv_data = s.recv(4096)
# rcv_data.decode()
# if rcv_data[:2] == 'c2':
# message = rcv_data[2:]
# if message[:3] == 'trn':
# temp = message[3]
# if temp == 2:
# turn = -1
# elif temp ==1:
# turn = 1
# elif message[:3] == 'num':
# self.set_text(message[3])
# elif message[:3] == 'txt':
# self.plainTextEdit_4.appendPlainText('client1: ' + message[3:])
# else:
print(rcv_data)
receive_parser()