Code archives/Networking/Message-based networking
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
This is a simplified form of the model used in the network module from duct. I recommend using types for each message, but I've to keep it out of this example for the sake of simplicity. See the comments below for example code (multiple source files). | |||||
' common.bmx Const MSGID_PING:Int = 10 Const MSGID_PONG:Int = 11 Type TBaseClient Extends TStream Abstract Field m_socket:TSocket, m_sip:Int Method Init(socket:TSocket) m_socket = socket If m_socket m_sip = m_socket.RemoteIP() End If End Method Method Read:Int(buf:Byte Ptr, count:Int) Return m_socket.Recv(buf, count) End Method Method Write:Int(buf:Byte Ptr, count:Int) Return m_socket.Send(buf, count) End Method Method ReadAvail:Int() Return m_socket.ReadAvail() End Method Method Eof:Int() If m_socket If m_socket.Connected() = True Return False End If End If Close() Return True End Method Method Close() If m_socket m_socket.Close() m_socket = Null End If End Method Method Connect:Int(remoteip:Int, remoteport:Int) m_sip = remoteip Return m_socket.Connect(remoteip, remoteport) End Method Method Connected:Int() If m_socket Return m_socket.Connected() End If Return False End Method Method Update() If Not Eof() If ReadAvail() > 0 HandleMessage(ReadInt()) End If End If End Method Method GetIPAddressAsInt:Int() Return m_sip End Method Method GetIPAddressAsString:String(separator:String = ".") Return (m_sip Shr 24) + separator + (m_sip Shr 16 & 255) + separator + (m_sip Shr 8 & 255) + separator + (m_sip & 255) End Method Method HandleMessage(id:Int) Abstract End Type |
Comments
| ||
Example code. server.bmx client.bmx |
| ||
"Ping from " + GetIPAddressAsString() Won't this just print the local IP and not the IP address of the sender? |
| ||
Won't this just print the local IP and not the IP address of the sender? No. GetIPAddressAsString is a method of TBaseClient which returns the socket's RemoteIP. |
| ||
First, thanks for this! I have what is probably a newbie question about this and/or Sockets in general. Is each Int sent in a separate packet or is it packed/optimized ? Can this code be quickly modified to transfer string lines instead of integers, or is this code far underneath that layer of control? I've read up on Stream Sockets where I could but I apologize if I'm asking confused questions. |
Code Archives Forum