[SFS DEBUG] UDPSocketLayer: Error reading data from socket: The remote host forcibly broke the existing connection.
[SFS DEBUG] Unexpected UDP I / O Error. Error reading data from socket: The remote host forcibly broke the existing connection.
[ConnectionReset]
What am I doing wrong?
Code: Select all
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Entities;
using Sfs2X.Requests;
using Sfs2X.Logging;
public class LobbyGUI : MonoBehaviour {
private SmartFox smartFox;
private string zone = "SimpleChat";
private string serverName = "127.0.0.1";
private int serverPort = 9933;
private string username = "";
private string loginErrorMessage = "";
private bool isLoggedIn;
private bool isJoining = false;
private string newMessage = "";
private ArrayList messages = new ArrayList();
// Locker to use for messages collection to ensure its cross-thread safety
private System.Object messagesLocker = new System.Object();
public GUISkin gSkin;
private Room currentActiveRoom;
private Vector2 gameScrollPosition, userScrollPosition, chatScrollPosition;
private int roomSelection = -1;
private string[] roomNameStrings;
private string[] roomFullStrings;
private Rect windowRect;
private bool showNewGameWindow;
private string roomName = "";
private int numMaxUsers = 4;
void Awake() {
Screen.showCursor = true;
Screen.lockCursor = false;
}
void Start()
{
bool debug = false;
if (SmartFoxConnection.IsInitialized)
{
smartFox = SmartFoxConnection.Connection;
}
else
{
smartFox = new SmartFox(debug);
}
smartFox.AddLogListener(LogLevel.INFO, OnDebugMessage);
}
private void AddEventListeners() {
smartFox.RemoveAllEventListeners();
smartFox.AddEventListener(SFSEvent.CONNECTION, OnConnection);
smartFox.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
smartFox.AddEventListener(SFSEvent.LOGIN, OnLogin);
smartFox.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
smartFox.AddEventListener(SFSEvent.LOGOUT, OnLogout);
smartFox.AddEventListener(SFSEvent.ROOM_JOIN, OnJoinRoom);
smartFox.AddEventListener(SFSEvent.PUBLIC_MESSAGE, OnPublicMessage);
smartFox.AddEventListener(SFSEvent.ROOM_CREATION_ERROR, OnCreateRoomError);
smartFox.AddEventListener(SFSEvent.USER_ENTER_ROOM, OnUserEnterRoom);
smartFox.AddEventListener(SFSEvent.USER_EXIT_ROOM, OnUserLeaveRoom);
smartFox.AddEventListener(SFSEvent.ROOM_ADD, OnRoomAdded);
smartFox.AddEventListener(SFSEvent.ROOM_REMOVE, OnRoomDeleted);
smartFox.AddEventListener(SFSEvent.USER_COUNT_CHANGE, OnUserCountChange);
smartFox.AddEventListener(SFSEvent.UDP_INIT, OnUdpInit);
}
void FixedUpdate() {
smartFox.ProcessEvents();
}
private void UnregisterSFSSceneCallbacks() {
// This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene
smartFox.RemoveAllEventListeners();
}
public void OnConnection(BaseEvent evt) {
bool success = (bool)evt.Params["success"];
string error = (string)evt.Params["errorMessage"];
Debug.Log("On Connection callback got: " + success + " (error : <" + error + ">)");
if (success) {
SmartFoxConnection.Connection = smartFox;
Debug.Log("Sending login request");
smartFox.Send(new LoginRequest(username, "", zone));
}
}
public void OnConnectionLost(BaseEvent evt) {
Debug.Log("OnConnectionLost");
isLoggedIn = false;
isJoining = false;
currentActiveRoom = null;
UnregisterSFSSceneCallbacks();
}
// Various SFS callbacks
public void OnLogin(BaseEvent evt) {
try {
bool success = true;
if (evt.Params.ContainsKey("success") && !(bool)evt.Params["success"]) {
loginErrorMessage = (string)evt.Params["errorMessage"];
Debug.Log("Login error: "+loginErrorMessage);
}
else {
Debug.Log("Logged in successfully");
// Startup up UDP
smartFox.InitUDP(serverName, serverPort);
}
}
catch (Exception ex) {
Debug.Log("Exception handling login request: "+ex.Message+" "+ex.StackTrace);
}
}
public void OnLoginError(BaseEvent evt) {
Debug.Log("Login error: "+(string)evt.Params["errorMessage"]);
}
public void OnUdpInit(BaseEvent evt) {
if (evt.Params.ContainsKey("success") && !(bool)evt.Params["success"]) {
loginErrorMessage = (string)evt.Params["errorMessage"];
Debug.Log("UDP error: "+loginErrorMessage);
} else {
Debug.Log("UDP ok");
PrepareLobby();
}
}
void OnLogout(BaseEvent evt) {
Debug.Log("OnLogout");
isLoggedIn = false;
isJoining = false;
currentActiveRoom = null;
smartFox.Disconnect();
}
public void OnDebugMessage(BaseEvent evt) {
string message = (string)evt.Params["message"];
Debug.Log("[SFS DEBUG] " + message);
}
public void OnJoinRoom(BaseEvent evt)
{
Room room = (Room)evt.Params["room"];
currentActiveRoom = room;
// If we joined a game room, then we either created it (and auto joined) or manually selected a game to join
if (room.IsGame) {
Debug.Log ("Joined game room " + room.Name);
UnregisterSFSSceneCallbacks();
Application.LoadLevel("game");
}
}
public void OnCreateRoomError(BaseEvent evt) {
string error = (string)evt.Params["errorMessage"];
Debug.Log("Room creation error; the following error occurred: " + error);
}
public void OnUserEnterRoom(BaseEvent evt) {
User user = (User)evt.Params["user"];
lock (messagesLocker) {
messages.Add(user.Name + " joined room");
}
}
private void OnUserLeaveRoom(BaseEvent evt) {
User user = (User)evt.Params["user"];
lock (messagesLocker) {
messages.Add(user.Name + " left room");
}
}
public void OnRoomAdded(BaseEvent evt) {
Room room = (Room)evt.Params["room"];
// Update view (only if room is game)
if ( room.IsGame ) {
SetupRoomList();
}
}
public void OnUserCountChange(BaseEvent evt) {
Room room = (Room)evt.Params["room"];
if (room.IsGame ) {
SetupRoomList();
}
}
/*
* Handle a room that was removed
*/
public void OnRoomDeleted(BaseEvent evt) {
SetupRoomList();
}
void OnPublicMessage(BaseEvent evt) {
try {
string message = (string)evt.Params["message"];
User sender = (User)evt.Params["sender"];
// We use lock here to ensure cross-thread safety on the messages collection
lock (messagesLocker) {
messages.Add(sender.Name + " said " + message);
}
chatScrollPosition.y = Mathf.Infinity;
Debug.Log("User " + sender.Name + " said: " + message);
}
catch (Exception ex) {
Debug.Log("Exception handling public message: "+ex.Message+ex.StackTrace);
}
}
// Finally draw all the lobby GUI
void OnGUI()
{
if (smartFox == null) return;
GUI.skin = gSkin;
int screenW = Screen.width;
int screenH = Screen.height;
GUI.Label(new Rect(2, -2, 680, 70), "", "SFSLogo");
// Login
if (!isLoggedIn) {
GUI.Label(new Rect(10, 90, 100, 100), "Username: ");
username = GUI.TextField(new Rect(100, 90, 200, 20), username, 25);
GUI.Label(new Rect(10, 120, 100, 100), "Invert Mouse Y: ");
OptionsManager.InvertMouseY = GUI.Toggle(new Rect(100, 120, 200, 20), OptionsManager.InvertMouseY, "");
GUI.Label(new Rect(10, 180, 100, 100), "Server: ");
serverName = GUI.TextField(new Rect(100, 180, 200, 20), serverName, 25);
GUI.Label(new Rect(10, 210, 100, 100), "Port: ");
serverPort = int.Parse(GUI.TextField(new Rect(100, 210, 200, 20), serverPort.ToString(), 4));
GUI.Label(new Rect(10, 240, 100, 100), loginErrorMessage);
if (GUI.Button(new Rect(100, 270, 100, 24), "Login") || (Event.current.type == EventType.keyDown && Event.current.character == '\n'))
{
AddEventListeners();
smartFox.Connect(serverName, serverPort);
}
}
else if (isJoining)
{
// Standard view
if (GUI.Button(new Rect(580, 478, 90, 24), "Logout"))
{
smartFox.Send( new LogoutRequest() );
}
GUI.Label(new Rect(498, 248, 180, 40), "Joining room");
}
else if (currentActiveRoom!=null)
{
// New game window
if (showNewGameWindow) {
windowRect = GUI.Window (0, windowRect, WindowFunction, "");
return;
}
// User list
GUI.Box (new Rect (screenW - 200, 80, 180, 170), "Users");
GUILayout.BeginArea (new Rect (screenW - 190, 110, 150, 160));
userScrollPosition = GUILayout.BeginScrollView (userScrollPosition, GUILayout.Width (150), GUILayout.Height (130));
GUILayout.BeginVertical ();
List<User> userList = currentActiveRoom.UserList;
foreach (User user in userList) {
GUILayout.Label (user.Name);
}
GUILayout.EndVertical ();
GUILayout.EndScrollView ();
GUILayout.EndArea ();
// Game room list
GUI.Box (new Rect (screenW - 200, 260, 180, 200), "Game List");
GUILayout.BeginArea (new Rect (screenW - 190, 290, 150, 130));
if (smartFox.RoomList.Count != 1) {
// We always have 1 non-game room - Main Lobby
gameScrollPosition = GUILayout.BeginScrollView (gameScrollPosition, GUILayout.Width (150), GUILayout.Height (160));
roomSelection = GUILayout.SelectionGrid (roomSelection, roomFullStrings, 1, "RoomListButton");
if (roomSelection >= 0 && roomNameStrings[roomSelection] != currentActiveRoom.Name) {
smartFox.Send(new JoinRoomRequest(roomNameStrings[roomSelection], null, smartFox.LastJoinedRoom.Id));
}
GUILayout.EndScrollView ();
} else {
GUILayout.Label ("No games available to join");
}
GUILayout.EndArea ();
if (GUI.Button (new Rect (screenW - 200, 480, 85, 24), "New game")) {
showNewGameWindow = true;
}
// Standard view
if (GUI.Button (new Rect (screenW - 105, 480, 85, 24), "Logout")) {
smartFox.Send( new LogoutRequest());
}
// Chat history
GUI.Box(new Rect(10, 80, 470, 390), "Chat");
GUILayout.BeginArea (new Rect(20, 110, 450, 350));
chatScrollPosition = GUILayout.BeginScrollView (chatScrollPosition, GUILayout.Width (450), GUILayout.Height (350));
GUILayout.BeginVertical();
// We use lock here to ensure cross-thread safety on the messages collection
lock (messagesLocker) {
foreach (string message in messages)
{
GUILayout.Label(message);
}
}
GUILayout.EndVertical();
GUILayout.EndScrollView ();
GUILayout.EndArea();
// Send message
newMessage = GUI.TextField(new Rect(10, 480, 370, 20), newMessage, 50);
if (GUI.Button(new Rect(390, 478, 90, 24), "Send") || (Event.current.type == EventType.keyDown && Event.current.character == '\n'))
{
smartFox.Send( new PublicMessageRequest(newMessage) );
newMessage = "";
}
}
}
private void PrepareLobby() {
SetupRoomList();
windowRect = new Rect (Screen.width / 2 - 160, Screen.height / 2 - 75, 320, 150);
showNewGameWindow = false;
isLoggedIn = true;
}
private void WindowFunction (int windowID) {
GUI.Box (new Rect (0, 0, 310, 150), "Create New Game");
GUI.BeginGroup (new Rect (10, 40, 310, 110));
// Room name row
GUI.Label (new Rect (0, 5, 80, 20), "Game name: ");
if (roomName.Equals ("")) {
roomName = smartFox.MySelf.Name + " game";
}
roomName = GUI.TextField (new Rect (new Rect (100, 5, 180, 20)), roomName);
// Max players row
GUI.Label (new Rect (0, 35, 80, 20), "Max players: ");
int tempMaxUsers;
if (int.TryParse (GUI.TextField (new Rect (100, 35, 80, 20), numMaxUsers.ToString (), 2), out tempMaxUsers)) {
numMaxUsers = tempMaxUsers;
}
// Button row
if (GUI.Button (new Rect (0, 70, 80, 20), "New game")) {
showNewGameWindow = false;
if (roomName.Equals("")) {
roomName = smartFox.MySelf.Name + " game";
}
/* TODO - create the room correctly
NewRoomDescriptor roomObj = new NewRoomDescriptor (roomName, numMaxUsers, true, 0, new ArrayList (), new NewRoomDescriptor.ExtensionDescriptor ("fpsExtension", "dk.fullcontrol.fpsdemo.FpsExtension"), "", true, true);
smartFox.CreateRoom (roomObj);
*/
RoomSettings settings = new RoomSettings(roomName);
settings.GroupId = "game";
settings.IsGame = true;
settings.MaxUsers = (short)numMaxUsers;
settings.MaxSpectators = 0;
settings.Extension = new RoomExtension(NetworkManager.ExtName, NetworkManager.ExtClass);
smartFox.Send(new CreateRoomRequest(settings, true, smartFox.LastJoinedRoom));
}
if (GUI.Button (new Rect (100, 70, 80, 20), "Cancel")) {
showNewGameWindow = false;
}
GUI.EndGroup ();
}
private void SetupRoomList () {
List<string> rooms = new List<string> ();
List<string> roomsFull = new List<string> ();
List<Room> allRooms = smartFox.RoomManager.GetRoomList();
foreach (Room room in allRooms) {
// Only show game rooms
if (!room.IsGame) {
continue;
}
Debug.Log ("Room id: " + room.Id + " has name: " + room.Name);
rooms.Add(room.Name);
roomsFull.Add(room.Name + " (" + room.UserCount + "/" + room.MaxUsers + ")");
}
roomNameStrings = rooms.ToArray();
roomFullStrings = roomsFull.ToArray();
if (smartFox.LastJoinedRoom==null) {
smartFox.Send(new JoinRoomRequest("The Lobby"));
}
}
}