Scripts:UDP Based Advert System

From BF2 Technical Information Wiki
Jump to navigation Jump to search

Introduction

There are many ways to implement an advert system in BF2. A good way would probably be to use the RCON interface. But another one that might be worth playing around with, is a solution where you create a dedicated advert port on the server, and send messages to it at will, using a suitable client.

Server Code

The idea is to let the server listen on a port bound to the 'localhost' interface, and read messages off that port, and post them to the players. The socket does of course need to be non-blocking, or it will interfere with the server. But I have no idea if the solution is to use a timer, like this code does. But this at least shows the consept:

import socket
import host
import bf2

port = 29600
addr = ('localhost',port)
bufsize = 1024

s = None
msgtimer = None

def init():
   global s, msgtimer
   print "Initializing the 'advert client' script."
   s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
   s.setblocking(0)
   s.bind(addr)
   msgtimer = bf2.Timer(read,1,1)
   msgtimer.setRecurring(1)


def read(data):
   if not s: return
   try:
      msg, client = s.recvfrom(bufsize)
   except:
      return False
   if msg:
      host.rcon_invoke("game.sayAll \"" + str(msg) + "\"")

Client Code

The client can be as easy or complex as anyone wish. This is the simplest possible client:

#!/usr/bin/env python import socket  HOST = 'localhost' PORT = 29600  print "Creating client socket." s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print "Sending data to server." s.sendto("Hi. I'm an advert client sending data to the server.", (HOST,PORT)) print "Closing socket." s.close()