Using socket to get Minecraft bots join through a proxy (Python) - python

I need help with my minecraft bot client. I have gotten it working, but I have a problem with socket, it keeps throwing me error codes all the time. Here is the "critical" part of the code:
def connect(ip, port, username, indelay, joindelay):
global running
if not running:
return;
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = s.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5,"183.60.143.121, 1080")
s.connect((ip, port))
login = (chr(len(username)+2) + chr(0) + chr(len(username)) + username).encode("utf-8")
s.sendall(handshake)
s.sendall(login)
print("Pelaaja "+username+" liittyi")
time.sleep(indelay/2)
s.sendall(('\x02\x16' + chr(2)).encode('utf-8'))
try:
for x in spam:
if(len(x)==0): continue
s.sendall(chat(x))
except socket.error:
pass
time.sleep(indelay/2)
s.close()
print("Pelaaja "+username+" lopetti")
time.sleep(joindelay)
connect(ip, port, getRandomUsername(), indelay, joindelay)'

Related

How to keep code running on client when server is offline

So i have a server and client program where the two programs communicate with each other.
my problem is when the server disconnects/goes offline the clients program immediately stops running.
how can i make it so the client program keeps running after the server goes off and keeps trying to connect every 20 seconds lets say so when the server goes back online it reconnects. Edit: I forgot to mention I know how to reconnect the main issue is getting the code to keep running instead of stoping when socket disconnects. Also I know for a fact the whole code works. It's If I close the terminal of the server program, then the clients program stops too.
part of client code to reconnect:
import socket
import os
import sys
import subprocess
import time
from time import sleep
s = socket.socket()
host = '192.168.2.16'
port = 9999
connected = False
while connected == False:
try:
s.connect((host,port))
connected = True
except socket.error:
sleep(5)
part of the server code:
import socket
import sys
import os
import threading
import time
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1,2]
queue = Queue()
all_connections = []
all_adresses = []
def socket_create():
try:
global s
global host
global port
host = '0.0.0.0'
port = 9999
s = socket.socket()
except socket.error as msg:
print("Error: " + str(msg))
def socket_bind():
try:
global host
global s
global port
print("Binding Socket To Port " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding Error: " + str(msg) + '/n' + "Trying Again...")
socket_bind()
def accept_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_adresses[:]
while 1:
try:
conn, address = s.accept()
conn.setblocking(1)
all_connections.append(conn)
all_adresses.append(address)
print("\nConnection has been established: " + address[0])
except:
print("Error accepting connections")
and error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Simple answer i found.
use try and except. simple as that.

Python3 Portscanner can't solve the socket pr0blem

When I run this code I am getting this socket error:
[WinError 10038] An operation was attempted on something that is not a socket
but even if I delete the s.close() it gives me wrong results.
It is a port scanner that are going to try connecting to all ports on the server I want to scan. And the ones that i'm getting connection from is stored in a list. But for some reason it is giving me wrong results. can someone please help me.
import socket
import threading
def scan_for_open_ports():
#Creating variables
OpenPorts = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
global port
global OpenPorts
port = 1
#Scanning
for i in range(65534):
try:
s.connect((host, port))
s.shutdown(2)
OpenPorts.append(port)
print(str(port) + 'is open.')
s.close()
port += 1
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
#Giving the user results
print('------Open porst-----\n')
print(OpenPorts)
That's because you're closing your socket inside the loop with s.close() and you're not opening it again and you try to connect with a socket that's closed already. you should close the socket when you're done with it at the end of the loop, i also amended your code to make OpenPorts global and remove the unnecessary port variable you define and increment inside your for loop
import socket
OpenPorts = []
def scan_for_open_ports():
# Creating variables
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
# Scanning
for port in range(1, 65534):
try:
s.connect((host, port))
OpenPorts.append(port)
print(str(port) + 'is open.')
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
# Giving the user results
print('------Open ports-----\n')
print(OpenPorts)
scan_for_open_ports()

Close socket when game ends

I wrote a script in blender game and I use sockets, I have a Server.blend and a client.blend.
this is my Server's Constructor:
class Server:
def __init__(self, host="127.0.0.1", port= 9238):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setblocking(False)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((host, port))
and this is my client's:
class Client:
def __init__(self, server_ip="127.0.0.1", server_port= 9238):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setblocking(False)
self.serv_addr = (server_ip, server_port)
The problem is that I don't know when the client is going to exit the game, so I can't close his socket- what keeps the used port open so i can't use the current port again.
I have a dictionary which contains all the addresses of all the clients, so I tried to send a message to all the addresses and in case that the client disconnected, i won't be able to send the message and use and exception to remove the address from the list (and it's avatar etc..):
def Check_For_Disconnect(self):
for addr in self.addr_user:
try:
self.socket.sendto(b"You are connected!" , addr)
except socket.error:
scene = logic.getCurrentScene()
for obj in scene.objects:
if str(obj) == "Text" and obj == self.addr_user[addr].name:
obj.delete()
del self.addr_user[addr]
I suppose that I don't reach the exception because the client's socket is still open so the message arrives properly.
Does anyone have any idea how I can around this problem?
The client should send some info about exiting the game, thus the server knows exactly when to close the socket. So the process is triggered by the client side.
I found a solution: I don't know when the client is going to exit the game, so I can't close his socket, what I do know is that just when the client runs his game- he can send messages to the server. so as long as the server on air he asks from the client for "connected" message. Every time that the server doesn't get a message from the client, he counts it. Now it's up to you how many counts to do until you sure that the client disconnected.
This is my receive method:
def receive(self):
while True:
for k in self.addr_connected:
if self.addr_connected[k] > 50:
self.Remove_Client(k)
break
try:
data, addr = self.socket.recvfrom(1024)
if not addr in self.addr_user:
user= User(data.decode())
scene = logic.getCurrentScene()
spawner = scene.objects['Spawner']
avatar = scene.addObject("Avatar", spawner)
avatar.children[0]['Text'] = user.name
avatar['user']= user
self.addr_user[addr] = user
self.addr_connected[addr] = 0
else:
user= self.addr_user[addr]
try:
user.keyboard.updateState(pickle.loads(data))
except:
data = data.decode()
if data == "I am connected":
self.addr_connected[addr] = 0
for k in self.addr_connected:
if k != addr:
self.addr_connected[k] += 1
except socket.error:
for k in self.addr_connected:
self.addr_connected[k] += 1
break

Python, recreate a socket and automatically reconnect

I'm writing a IRC bot in Python.
Source: http://pastebin.com/gBrzMFmA ( sorry for pastebin, i don't know how to efficently/correctly use the code tagthing on here )
When the "irc" socket dies, is there anyway I could go about detecting if its dead and then automatically reconnecting?
I was googling for awhile now and found that I would have to create a new socket. I was trying and added stuff like catching socket.error in the while True: but it seems to just hang and not reconnect correctly..
Thanks for help in advance
Answered here: Python : Check if IRC connection is lost (PING PONG?)
While the question owner's accepted answer works, I prefer John Ledbetter's answer here, soley for its simplicity: https://stackoverflow.com/a/6853352/625919
So, for me, I have something along the lines of
def connect():
global irc
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((server, port))
#and nick, pass, and join stuffs
connect()
while True:
data = irc.recv(4096)
if len(data) == 0:
print "Disconnected!"
connect()
This is the code for Re-Connect socket
import socket
import time
username = "Manivannan"
host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
print("Server not connected")
while True:
if(not connected):
try:
s.connect((host, port))
print("Server connected")
connected = True
except:
pass
else:
try:
s.sendall(username.encode('utf-8'))
except:
print("Server not connected")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
pass
time.sleep(5)
s.close()

Python Server send data not working

I am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)

Categories

Resources