\I want to make a socket application that will run on Linux and provide multiple messaging and file transfer. Can you share sample code? Can you help me i am a second year computer engineering student?
I found a similar code in my research, but I cannot connect to my linux server from different computers.I learned this code from github #HondaPL.
This is client codes
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using MessengerLogic;
using System.IO;
namespace Messenger
{
public class Connection
{
public static int BufferSize = 1024;
public static string nick;
public static IPAddress ip = IPAddress.Parse("-.-.-.-");
public static int port = 1234;
public static TcpClient client = new TcpClient();
public static List<string> users = new List<string>();
public static bool isEnd = false;
public static string[] fromServer = new string[30];
public void Connect(string nickname)
{
nick = nickname;
client.Connect(ip, port);
nickname += "$Welcome$";
byte[] buffer = Encoding.ASCII.GetBytes(nickname);
NetworkStream ns = client.GetStream();
Console.WriteLine(nickname);
ns.Write(buffer, 0, buffer.Length);
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
StringParser parser = new StringParser();
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
fromServer = new string[30];
users.Clear();
string message = Encoding.ASCII.GetString(receivedBytes, 0, byte_count);
fromServer = parser.Parser(message);
if (fromServer[0] == "List")
{
for (int i = 1; i < fromServer.Length; i++)
{
users.Add(fromServer[i]);
}
isEnd = true;
}
else
{
Console.WriteLine(message);
Console.WriteLine(fromServer[0]);
Console.WriteLine(fromServer[1]);
FrmOnlineUsers.frm.AssignValues(fromServer[0], fromServer[1]);
FrmOnlineUsers.frm.MessageFromClient();
}
}
}
public List<string> Refresh()
{
NetworkStream ns = client.GetStream();
string temp = nick;
temp += "$List$";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
while (!isEnd)
{
}
isEnd = false;
return users;
}
public void SendMessage(string who, string msg)
{
NetworkStream ns = client.GetStream();
string temp = $"{who}$Message${msg}$";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
}
public void FileSend(string filepath, string nick, string fileName)
{
NetworkStream ns = client.GetStream();
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
byte[] bytesToSend = new byte[fs.Length];
int numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length);
int totalBytes = 0;
//Tutaj trzeba dodać, aby pobierał nazwę pliku
string temp = $"{nick}$File${fileName}${fs.Length}";
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(temp);
ns.Write(buffer, 0, buffer.Length);
Thread.Sleep(1000);
for (int i = 0; i <= fs.Length / BufferSize; i++)
{
if (fs.Length - (i * BufferSize) > BufferSize)
{
ns.Write(bytesToSend, i * BufferSize,
BufferSize);
totalBytes += BufferSize;
}
else
{
ns.Write(bytesToSend, i * BufferSize,
(int)fs.Length - (i * BufferSize));
totalBytes += (int)fs.Length - (i * BufferSize);
}
}
fs.Close();
}
}
}
Related
I have a code that saves data in the data file are saved without any problem.But I also tried to save an array but the array was not saved and I get an error.I keep the data (and also the array) in BinaryFormatter.The error indicates the line bf.Serialize (file, data) before closing the file in the save function.
the code
public class SaveLoadScript : MonoBehaviour
{
public int allMoneyOfplayer, allXpOfPlayer, laval, maxXp, howMuchUpMaxXp;
public float highTime;
public List<GunScript> gun = new List<GunScript>();
public void Start()
{
Save();
}
public void Update()
{
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/saveG.file");
PlayerData data = new PlayerData();
data.money = allMoneyOfplayer;
data.xp = allXpOfPlayer;
if (highTime > data.time)
data.time = highTime;
data.laval = laval;
data.maxXp = maxXp;
data.howMuchUpMaxXp = howMuchUpMaxXp;
for (int i = 0; i < gun.Count; i++)
data.gun.Add(gun[i]);
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/saveG.file"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/saveG.file", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
allMoneyOfplayer = data.money;
allXpOfPlayer = data.xp;
highTime = data.time;
laval = data.laval;
maxXp = data.maxXp;
howMuchUpMaxXp = data.howMuchUpMaxXp;
file.Close();
}
}
}
[System.Serializable]
class PlayerData
{
public int money;
public int xp;
public float time;
public int laval;
public int maxXp;
public int howMuchUpMaxXp;
public List<GunScript> gun = new List<GunScript>();
}
the error
SerializationException: Type 'GunScript' in Assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers (System.RuntimeType type) (at :0)
System.Runtime.Serialization.FormatterServices+<>c__DisplayClass9_0.b__0 (System.Runtime.Serialization.MemberHolder _) (at :0)
System.Collections.Concurrent.ConcurrentDictionary2[TKey,TValue].GetOrAdd (TKey key, System.Func2[T,TResult] valueFactory) (at :0)
System.Runtime.Serialization.FormatterServices.GetSerializableMembers (System.Type type, System.Runtime.Serialization.StreamingContext context) (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo () (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize (System.Type objectType, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.SerializationBinder binder) (at :0)
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize (System.Type objectType, System.Runtime.Serialization.ISurrogateSelector surrogateSelector, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.Formatters.Binary.SerObjectInfoInit serObjectInfoInit, System.Runtime.Serialization.IFormatterConverter converter, System.Runtime.Serialization.SerializationBinder binder) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.WriteArray (System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo objectInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo memberNameInfo, System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo memberObjectInfo) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write (System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo objectInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo memberNameInfo, System.Runtime.Serialization.Formatters.Binary.NameInfo typeNameInfo) (at :0)
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize (System.Object graph, System.Runtime.Remoting.Messaging.Header[] inHeaders, System.Runtime.Serialization.Formatters.Binary.__BinaryWriter serWriter, System.Boolean fCheck) (at :0)
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize (System.IO.Stream serializationStream, System.Object graph, System.Runtime.Remoting.Messaging.Header[] headers, System.Boolean fCheck) (at :0)
[System.Serializable] //<-- add this attribute
public class GunScript
I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading
I am trying to setup a multiplayer game to be played through a browser using UNet. In the editor everything works fine, I followed a tutorial (https://www.youtube.com/watch?v=qGkkaNkq8co) that said it should work in webgl but sadly it does not. There are two scripts as of yet one for the client and one for the server linked below. This is using mostly the LLAPI.
Whether I use the networkServer.usewebsocket = true or not, the result is the same.
The debug of "finished connection" does show so it completes the OnConnection function.
From the editor everything works fine but from the browser I get the following error:
"Attempt to send to not connected connection {1}" -- Since I get this error when ASKNAME is asked and when ASKPOSITION is asked I suspect that the SEND function is the problem im trying to send something the browser cant understand. But I don't know why.
private int port = 3001;
private List<ServerClient> clients = new List<ServerClient>();
private float lastMovementUpdate;
private float movementUpdateRate = 0.05f;
private int socketId;
private int webHostId;
private int reliableChannel;
private int unReliableChannel;
private bool isStarted = false;
private byte error;
private void Start()
{
NetworkTransport.Init();
ConnectionConfig cc = new ConnectionConfig();
reliableChannel = cc.AddChannel(QosType.Reliable);
unReliableChannel = cc.AddChannel(QosType.Unreliable);
HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
socketId = NetworkTransport.AddHost(topo, port, null);
webHostId = NetworkTransport.AddWebsocketHost(topo, port, null);
isStarted = true;
}
private void Update()
{
if (!isStarted)
return;
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData)
{
case NetworkEventType.Nothing: //1
break;
case NetworkEventType.ConnectEvent: //2
Debug.Log("Player " + connectionId + "has connected");
OnConnection(connectionId);
break;
case NetworkEventType.DataEvent: //3
string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
Debug.Log("Receiving From " + connectionId + "has sent : " + msg);
string[] splitData = msg.Split('|');
switch (splitData[0])
{
case "NAMEIS":
OnNameIS(connectionId, splitData[1]);
break;
case "MYPOSITION":
OnMyPosition(connectionId, float.Parse(splitData[1]), float.Parse(splitData[2]));
break;
default:
Debug.Log("invalid message : " + msg);
break;
}
break;
case NetworkEventType.DisconnectEvent: //4
Debug.Log("Player " + connectionId + "has disconnected");
OnDiconnection(connectionId);
break;
}
if (clients.Count > 0)
{
if (Time.time - lastMovementUpdate > movementUpdateRate)
{
lastMovementUpdate = Time.time;
string posMsg = "ASKPOSITION|";
foreach (ServerClient sc in clients)
posMsg += sc.connectionId.ToString() + '%' + sc.position.x.ToString() + '%' + sc.position.y.ToString() + '|';
posMsg = posMsg.Trim('|');
Send(posMsg, unReliableChannel, clients);
}
}
}
private void OnConnection(int cnnId)
{
Debug.Log("Arrived at connection");
ServerClient c = new ServerClient();
c.connectionId = cnnId;
c.playerName = "TEMP";
clients.Add(c);
string msg = "ASKNAME|" + cnnId + "|";
foreach (ServerClient sc in clients)
msg += sc.playerName + '%' + sc.connectionId + '|';
msg = msg.Trim('|');
Send(msg, reliableChannel, cnnId);
Debug.Log("Finished at connection");
}
private void OnNameIS(int cnnId, string playerName)
{
// link the name to the connection ID
clients.Find(x => x.connectionId == cnnId).playerName = playerName;
// Tell evertone that a new player has connected
Send("CNN|" + playerName + '|' + cnnId, reliableChannel, clients);
}
private void Send(string message, int channelId, int cnnId)
{
List<ServerClient> c = new List<ServerClient>();
c.Add(clients.Find(x => x.connectionId == cnnId));
Send(message, channelId, c);
}
private void Send(string message, int channelId, List<ServerClient> c)
{
Debug.Log("sending : " + message);
byte[] msg = Encoding.Unicode.GetBytes(message);
foreach(ServerClient sc in c)
{
NetworkTransport.Send(socketId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
}
}
private void OnDiconnection(int cnnId)
{
clients.Remove(clients.Find(x => x.connectionId == cnnId));
string msg = "DC|" + cnnId;
Send(msg, reliableChannel, clients);
}
private void OnMyPosition(int cnnId, float x, float y)
{
clients.Find(clientInQuestion => clientInQuestion.connectionId == cnnId).position = new Vector3(x, y, 0);
}
And then the client:
private const int MAX_CONNECTION = 100;
private int port = 3001;
private int hostId;
private int webHostId;
private int reliableChannel;
private int unReliableChannel;
private int connectionId;
private int clientId;
private bool isConnected = false;
public bool isStarted = false;
private float connectionTime;
private string playerName;
private byte error;
public GameObject playerPrefab;
public Dictionary<int, player> players = new Dictionary<int, player>();
public void Connect()
{
Debug.Log("connecting...");
// does player have a name?
string pName = GameObject.Find("NameInput").GetComponent<InputField>().text;
if (pName == "")
{
Debug.Log("Enter a name");
return;
}
playerName = pName;
NetworkTransport.Init();
ConnectionConfig cc = new ConnectionConfig();
reliableChannel = cc.AddChannel(QosType.Reliable);
unReliableChannel = cc.AddChannel(QosType.Unreliable);
HostTopology topo = new HostTopology(cc, MAX_CONNECTION);
hostId = NetworkTransport.AddHost(topo, 0);
connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);
connectionTime = Time.time;
isConnected = true;
Debug.Log("connected");
}
private void Update()
{
connectionTime += Time.deltaTime;
if (!isConnected)
return;
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData)
{
case NetworkEventType.DataEvent:
string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
Debug.Log("receiving : " + msg);
string[] splitData = msg.Split('|');
switch (splitData[0])
{
case "ASKNAME":
OnAskName(splitData);
break;
case "CNN":
SpawnPlayer(splitData[1], int.Parse(splitData[2]));
break;
case "DC":
playerDisconnected(int.Parse(splitData[1]));
break;
case "ASKPOSITION":
OnAskPosition(splitData);
break;
default:
Debug.Log("invalid message : " + msg);
break;
}
break;
}
}
private void OnAskName(string[] data)
{
// set the client ID
clientId = int.Parse(data[1]);
// send our name to the server
Send("NAMEIS|" + playerName, reliableChannel);
// create all the other players
for (int i = 2; i < data.Length - 1; i++)
{
string[] d = data[i].Split('%');
SpawnPlayer(d[0], int.Parse(d[1]));
}
}
private void OnAskPosition(string[] data)
{
if (!isStarted)
return;
//update everyone else
for (int i = 1; i <= data.Length-1; i++)
{
string[] d = data[i].Split('%');
//prevent the server from updating us
if (clientId != int.Parse(d[0]))
{
Debug.Log("updating position");
Vector3 position = Vector3.zero;
position.x = float.Parse(d[1]);
position.y = float.Parse(d[2]);
players[int.Parse(d[0])].avatar.transform.position = position;
}
}
//send out own position
Vector3 myPosition = players[clientId].avatar.transform.position;
string m = "MYPOSITION|" + myPosition.x.ToString() + '|' + myPosition.y.ToString();
Send(m, unReliableChannel);
}
private void SpawnPlayer(string playerName, int cnnId)
{
GameObject go = Instantiate(playerPrefab) as GameObject;
// is this ours?
if(cnnId == clientId)
{
// add mobility
go.AddComponent<PlayerController>();
// remove Canvas
GameObject.Find("Canvas").SetActive(false);
isStarted = true;
}
player p = new player();
p.avatar = go;
p.playerName = playerName;
p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
p.connectionId = cnnId;
players.Add(cnnId, p);
}
private void Send(string message, int channelId)
{
Debug.Log("sending : " + message);
byte[] msg = Encoding.Unicode.GetBytes(message);
NetworkTransport.Send(hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
}
private void playerDisconnected(int cnnId)
{
Destroy(players[cnnId].avatar);
Debug.Log("player : " + players[cnnId].playerName + " has disconnected");
players.Remove(cnnId);
}
}
Any feedback would be greatly appreciated, I have tried looking through the documentation but I feel I have done everything that it says to do in that (https://docs.unity3d.com/Manual/UNetUsingTransport.html) at the bottom it talks about webgl support, but it doesn't seem to have worked.
Fixed this issue,
Answer was that I was sending to HostID and not webSocketId
so this:
private void Send(string message, int channelId, List<ServerClient> c)
{
Debug.Log("sending : " + message);
byte[] msg = Encoding.Unicode.GetBytes(message);
foreach(ServerClient sc in c)
{
NetworkTransport.Send(hostId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
}
}
was changed to this:
private void Send(string message, int channelId, List<ServerClient> c)
{
Debug.Log("sending : " + message);
byte[] msg = Encoding.Unicode.GetBytes(message);
foreach(ServerClient sc in c)
{
NetworkTransport.Send(webSocketId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
}
}
I'm following a tutorial unity multiplayer (UNET) on YouTube but I'm getting different results compared to the guy in the video. You see I followed his tutorial to the tea, however in my server script within the update function I used a debug.log in the switch statement default function to tell me if i'm receiving invalid messaging, which I am. I think that my message isn't really being sent properly despite the fact that I followed the guy's tutorial carefully! Am I missing something in my server script?
This is my code:
public class ServerClient
{
public int connectionId;
public string playerName;
}
public class Server : MonoBehaviour {
private const int MAX_CONNECTION = 4;
private int port = 8888;
private int hostId;
private int webHostId;
private int reliableChannel;
private int unreliableChannel;
private bool isStarted = false;
private byte error;
private List<ServerClient> clients = new List<ServerClient>();
private void Start()
{
NetworkTransport.Init ();
ConnectionConfig cc = new ConnectionConfig ();
reliableChannel = cc.AddChannel (QosType.Reliable);
unreliableChannel = cc.AddChannel (QosType.Unreliable);
HostTopology topo = new HostTopology (cc, MAX_CONNECTION);
hostId = NetworkTransport.AddHost (topo, port); // null
Debug.Log ("Socket Open. hostId is: " + hostId);
webHostId = NetworkTransport.AddWebsocketHost (topo, port, null); //, port, null
isStarted = true;
}
private void Update()
{
if (!isStarted)
return;
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = NetworkTransport.Receive (out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData) {
case NetworkEventType.ConnectEvent: //2
Debug.Log ("Player " + connectionId + "has connected");
OnConnection (connectionId);
break;
case NetworkEventType.DataEvent: //3
string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
//Debug.Log("Player" + connectionId + " has sent : " + msg);
Debug.Log("Recieving from " + connectionId + " : " + msg);
string[] splitData = msg.Split ('|');
switch (splitData[0])
{
case "OnNameIs":
OnNameIs (connectionId, splitData [1]);
break;
default:
Debug.Log ("Invalid message: " + msg);
break;
}
break;
case NetworkEventType.DisconnectEvent: // 4
Debug.Log("Player " + connectionId + "has disconnected");
break;
}
}
private void OnConnection(int cnnId)
{
// This may add a thrid player
ServerClient c = new ServerClient();
c.connectionId = cnnId;
c.playerName = "TEMP";
clients.Add(c);
//So you might want to change this later
string msg = "AskName|" + cnnId + "|";
foreach (ServerClient sc in clients)
msg += sc.playerName + '%' + sc.connectionId + '|';
msg = msg.Trim ('|');
Send (msg, reliableChannel, cnnId);
}
private void OnNameIs(int cnnId, string playerName)
{
clients.Find (x => x.connectionId == cnnId).playerName = playerName;
Send ("CNN|" + playerName + '|' + cnnId, reliableChannel, clients);
}
private void Send(string message, int channelId, int cnnId)
{
List<ServerClient> c = new List<ServerClient>();
c.Add (clients.Find (x => x.connectionId == cnnId));
Send (message, channelId, c);
}
private void Send(string message, int channelId, List<ServerClient> c)
{
Debug.Log ("Sending : " + message);
byte[] msg = Encoding.Unicode.GetBytes (message);
foreach (ServerClient sc in c)
{
NetworkTransport.Send (hostId, sc.connectionId, channelId, msg, message.Length * sizeof(char), out error);
}
}
}
The below script is my client script:
public class Player
{
public string playerName;
public GameObject avatar;
public int connectionId;
}
public class Client : MonoBehaviour {
private const int MAX_CONNECTION = 4;
private int port = 8888; //5701
private int hostId;
private int webHostId;
private int connectionId;
private int ourClientId;
private int reliableChannel;
private int unreliableChannel;
private float connectionTime;
private bool isConnected = false;
private bool isStarted = false;
private byte error;
private string playerName;
public GameObject playerPrefab;
public List<Player> players = new List<Player>();
public void Connect()
{
//Does the player have a name?
//take this part out
string pName = GameObject.Find("NameInput").GetComponent<InputField>().text;
if (pName == "") {
Debug.Log ("you must enter a name");
return;
}
playerName = pName;
//
// place this is the Start fuction
NetworkTransport.Init ();
ConnectionConfig cc = new ConnectionConfig ();
reliableChannel = cc.AddChannel (QosType.Reliable);
unreliableChannel = cc.AddChannel (QosType.Unreliable);
HostTopology topo = new HostTopology (cc, MAX_CONNECTION);
hostId = NetworkTransport.AddHost (topo, 0);
//
byte error;
connectionId = NetworkTransport.Connect (hostId, "127.0.0.1", port, 0, out error);
Debug.Log ("Connection to server. ConnectionId: " + connectionId);
connectionTime = Time.time;
isConnected = true;
}
private void Update()
{
if (!isConnected)
return;
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = NetworkTransport.Receive (out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData) {
case NetworkEventType.DataEvent: //1
string msg = Encoding.Unicode.GetString (recBuffer, 0, dataSize);
Debug.Log ("Recieving : " + msg);
string[] splitData = msg.Split ('|');
switch (splitData[0])
{
case "AskName":
OnAskName (splitData);
break;
case "CNN":
SpawnPlayer (splitData[1], int.Parse(splitData[2]));
break;
case "DC":
break;
default:
Debug.Log ("Invalid message: " + msg);
break;
}
break;
}
}
private void OnAskName(string[] data)
{
ourClientId = int.Parse (data [1]);
Send ("OnNameis|" + playerName, reliableChannel);
for (int i = 2; i < data.Length - 1; i++)
{
string[] d = data[i].Split('%');
SpawnPlayer(d[0], int.Parse(d[1]));
}
}
private void SpawnPlayer(string playerName, int cnnId)
{
GameObject go = Instantiate (playerPrefab) as GameObject;
Debug.Log ("Object has been spawn", go);
if (cnnId == ourClientId) // the problem //
{
GameObject.Find("Canvas").SetActive (false);
isStarted = true;
}
Player p = new Player ();
p.avatar = go;
p.playerName = playerName;
p.connectionId = cnnId;
p.avatar.GetComponentInChildren<TextMesh>().text = playerName;
players.Add (p);
}
private void Send(string message, int channelId)
{
Debug.Log ("Sending : " + message);
byte[] msg = Encoding.Unicode.GetBytes (message);
NetworkTransport.Send (hostId, connectionId, channelId, msg, message.Length * sizeof(char), out error);
}
Thank you in advance!
Not quite to the tea.
If you look closely you'll see that:
The client sends a command with the name OnNameis
While the server expects a command named OnNameIs
This pretty much illustrates the dangers of using strings for commands. Use an Enum instead.
When I run the following code on Windows 7 and 8.1 I get different results. On Windows 7 if I re-run the code on the newly created file it throws exceptions while the Windows 8.1 code works fine.
Any Clues?????
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string a = #"C:\temp\Materials\20130911134612877_3.pdf";
string b = #"C:\temp\Materials\20130911134612877_4.pdf";
Program p = new Program();
p.Open(a);
p.SaveSource(b);
}
public List<Bitmap> Bitmaps { get; private set; }
private string sourceFileName { get; set; }
private string destPath { get; set; }
public List<int> Source { get; set; }
public List<int> Destination { get; set; }
public void Open(string fileName)
{
this.sourceFileName = fileName;
this.destPath = Path.Combine(Path.GetDirectoryName(fileName), "Processed");
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(this.destPath);
}
string original = Path.Combine(Path.GetDirectoryName(fileName), "Orginal", Path.GetFileName(fileName));
if (!File.Exists(original))
{
string originalPath = Path.GetDirectoryName(original);
if (!Directory.Exists(originalPath))
{
Directory.CreateDirectory(originalPath);
}
File.Copy(fileName, original);
}
if (this.Bitmaps != null)
{
for (int _i = 0; _i < this.Bitmaps.Count; _i++)
{
this.Bitmaps[_i].Dispose();
}
}
PDFDocument doc = GetDocument(fileName);
this.Bitmaps = new List<Bitmap>();
this.Source = new List<int>();
this.Destination = new List<int>();
for (int i = 0; i < doc.Count; i++)
{
this.Source.Add(i);
this.Bitmaps.Add(doc.GetImage(i));
}
doc.Close();
}
public void SaveSource(string file)
{
if (this.Source.Count != 0)
{
PDFDocument pdf = new PDFDocument();
pdf.FileName = file;
foreach (int i in this.Source)
{
pdf.Add(this.Bitmaps[i]);
}
pdf.Close();
}
else
{
if (File.Exists(this.sourceFileName))
{
File.Delete(this.sourceFileName);
}
}
}
private PDFDocument GetDocument(string file)
{
PDFDocument doc = null;
doc = new PDFDocument();
doc.Open(file);
return doc;
}
public static void MergePdfFiles(IEnumerable<string> files, string output)
{
iTextSharp.text.Document doc;
iTextSharp.text.pdf.PdfCopy pdfCpy;
doc = new iTextSharp.text.Document();
pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(output, System.IO.FileMode.Create));
doc.Open();
foreach (string file in files)
{
// initialize a reader
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
int pageCount = reader.NumberOfPages;
// set page size for the documents
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
for (int pageNum = 1; pageNum <= pageCount; pageNum++)
{
iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, pageNum);
pdfCpy.AddPage(page);
}
reader.Close();
}
doc.Close();
}
}
public class MyImageRenderListener : IRenderListener
{
public void RenderText(TextRenderInfo renderInfo) { }
public void BeginTextBlock() { }
public void EndTextBlock() { }
public Bitmap Image = null;
public void RenderImage(ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.GetImage();
if (image == null) return;
using (MemoryStream ms = new MemoryStream(image.GetImageAsBytes()))
{
Bitmap i = (System.Drawing.Bitmap)Bitmap.FromStream(ms);
Image = (System.Drawing.Bitmap)i.Clone();
i.Dispose();
// int dpi = i.Height / 11;
int yDPI = Image.Height / 11;
int xDPI = (Image.Width * 2) / 17;
xDPI = Math.Abs(xDPI - 300) < 10 ? 300 : xDPI;
yDPI = Math.Abs(yDPI - 300) < 10 ? 300 : yDPI;
xDPI = Math.Abs(xDPI - 600) < 10 ? 600 : xDPI;
yDPI = Math.Abs(yDPI - 600) < 10 ? 600 : yDPI;
if (xDPI == yDPI)
{
Image.SetResolution(xDPI, yDPI);
}
else
{
}
}
}
catch (IOException)
{
/*
* pass-through; image type not supported by iText[Sharp]; e.g. jbig2
*/
}
}
}
public class PDFDocument
{
public string FileName { get; set; }
~PDFDocument()
{
this.Close();
}
public static void AddImage(Stream inputPdfStream, Stream outputPdfStream, Stream inputImageStream)
{
PdfReader reader = new PdfReader(inputPdfStream);
iTextSharp.text.Rectangle size = reader.GetPageSize(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(size.Width - 98, size.Height - 98);
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
int page = 1;
// for (int page = 1; page <= reader.NumberOfPages; page++)
{
PdfContentByte pdfContentByte = stamper.GetOverContent(page);
pdfContentByte.AddImage(image);
}
stamper.Close();
}
public void Open(string fileName)
{
this.reader = new PdfReader(fileName);
this.parser = new PdfReaderContentParser(reader);
this.listener = new MyImageRenderListener();
}
public int Count { get { return reader.NumberOfPages; } }
public Bitmap GetImage(int index)
{
parser.ProcessContent(index + 1, listener);
return listener.Image;
}
public Bitmap GetImage2(int index)
{
PdfDictionary page = reader.GetPageN(index + 1);
return GetImagesFromPdfDict(page);
}
private PdfReaderContentParser parser = null;
private MyImageRenderListener listener = null;
private PdfReader reader = null;
private Bitmap GetImagesFromPdfDict(PdfDictionary dict)
{
PdfDictionary res = (PdfDictionary)(PdfReader.GetPdfObject(dict.Get(PdfName.RESOURCES)));
PdfDictionary xobj = (PdfDictionary)(PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT)));
Bitmap bm = null;
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)(PdfReader.GetPdfObject(obj));
PdfName subtype = (PdfName)(PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)));
if (PdfName.IMAGE.Equals(subtype))
{
int xrefIdx = ((PRIndirectReference)obj).Number;
PdfObject pdfObj = this.reader.GetPdfObject(xrefIdx);
PRStream str = (PRStream)(pdfObj);
iTextSharp.text.pdf.parser.PdfImageObject pdfImage = new iTextSharp.text.pdf.parser.PdfImageObject(str);
bm = (System.Drawing.Bitmap)pdfImage.GetDrawingImage();
bm.SetResolution(300.0f, 300.0f);
break;
}
else if (PdfName.FORM.Equals(subtype) || PdfName.GROUP.Equals(subtype))
{
GetImagesFromPdfDict(tg);
}
}
}
}
return bm;
}
public void Split(string fileName)
{
throw new NotImplementedException();
}
public void Save(System.Drawing.Bitmap bm, string filename)
{
Save(bm, filename, RotateFlipType.RotateNoneFlipNone);
}
const float PAGE_LEFT_MARGIN = 0;
const float PAGE_RIGHT_MARGIN = 0;
const float PAGE_TOP_MARGIN = 0;
const float PAGE_BOTTOM_MARGIN = 0;
public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate)
{
Bitmap image = bm;
if (rotate != RotateFlipType.RotateNoneFlipNone)
{
image.RotateFlip(rotate);
}
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN))
{
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
pdfDocument.Open();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
pdfDocument.Add(img);
pdfDocument.Close();
writer.Close();
}
}
}
public void Add(System.Drawing.Bitmap bm)
{
this.Add(bm, RotateFlipType.RotateNoneFlipNone);
}
FileStream stream;
iTextSharp.text.Document pdfDocument;
iTextSharp.text.pdf.PdfWriter writer;
public void Add(System.Drawing.Bitmap bm, System.Drawing.RotateFlipType rotate)
{
if (this.stream == null)
{
this.stream = new FileStream(this.FileName, FileMode.Create);
this.pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN);
this.writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
this.pdfDocument.Open();
}
Bitmap image = bm;
if (rotate != RotateFlipType.RotateNoneFlipNone)
{
image.RotateFlip(rotate);
}
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
ms.Seek(0, SeekOrigin.Begin);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
pdfDocument.Add(img);
}
}
public void Close()
{
if (this.pdfDocument != null)
{
this.pdfDocument.Close();
this.pdfDocument.Dispose();
this.writer.Close();
this.writer.Dispose();
this.stream.Close();
this.stream.Dispose();
this.pdfDocument = null;
this.writer = null;
this.pdfDocument = null;
}
if (this.reader != null)
{
this.reader.Close();
}
}
public void Tag(string oldFile, Stream fs, string text)
{
float x;
float y;
// open the reader
PdfReader reader = new PdfReader(oldFile);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
float height = 60;
float width = 150;
x = size.Width - 40 - width;
y = size.Height - height;
Document document = new Document(size);
// open the writer
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
cb.Rectangle(x, y, width, height);
cb.SetColorFill(BaseColor.WHITE);
cb.Fill();
// close the streams and voilá the file should be changed :)
// write the text in the pdf content
cb.BeginText();
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 20);
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x + 5, y + 10, 0);
cb.EndText();
writer.Flush();
document.Close();
reader.Close();
// fs.Seek(0, SeekOrigin.Begin);
}
}
}
I have created a simple client/server app and it works great (1MB/s which is max speed i set for server to send) when i run in locally or under Lan network. But when i try to run it in one of my Dedicate Server/VPS my download speed become slow.
I am using CentOS on servers and Mono for running it, Mono version is 2.10.2 and CentOs is 64bit version. Created using framework 4.
Speed test:
Local: 1MB
Lan: 1MB
Running server on CentOS: 0~10~20 KB
My connection speed is 2Mb or ~250KB. It will give me full speed some times. But very rare and i cant see why it give my full speed sometimes and sometimes no speed at all or why sometimes only 10KB and other times only 20KB. Also, i am running client part on my Win7 Desktop. Here is code for server and client part:
Server:
class Program
{
private static BackgroundWorker _ListeningWorker;
private static BackgroundWorker _QWorker;
private static System.Net.Sockets.Socket _Server;
private static List<System.Net.Sockets.Socket> ConnectedClients = new List<System.Net.Sockets.Socket>();
static void Main(string[] args)
{
Program._ListeningWorker = new BackgroundWorker();
Program._ListeningWorker.WorkerSupportsCancellation = true;
Program._ListeningWorker.DoWork += _ListeningWorker_DoWork;
Program._QWorker = new BackgroundWorker();
Program._QWorker.WorkerSupportsCancellation = true;
Program._QWorker.DoWork += _QWorker_DoWork;
Program.Start();
while (true)
{
Console.Clear();
Console.WriteLine("1.0.0.1");
Console.WriteLine(Program.ConnectedClients.Count.ToString());
System.Threading.Thread.Sleep(1000);
}
}
public static bool Start()
{
if (!Program._ListeningWorker.IsBusy)
{
Program._Server = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8081);
Program._Server.Bind(ipLocal);
Program._Server.Listen(10);
Program._ListeningWorker.RunWorkerAsync();
Program._QWorker.RunWorkerAsync();
}
return true;
}
private static void _ListeningWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!Program._ListeningWorker.CancellationPending)
{
if (Program._Server.Poll(10, SelectMode.SelectRead))
{
lock (ConnectedClients)
{
Program.ConnectedClients.Add(Program._Server.Accept());
}
}
System.Threading.Thread.Sleep(1);
}
Program._Server.Close();
}
private static void _QWorker_DoWork(object sender, DoWorkEventArgs e)
{
byte[] array = new byte[1024];
Random random = new Random();
while (!Program._QWorker.CancellationPending)
{
if (ConnectedClients.Count > 0)
{
System.Net.Sockets.Socket[] st;
lock (ConnectedClients)
{
st = new System.Net.Sockets.Socket[Program.ConnectedClients.Count];
ConnectedClients.CopyTo(st);
}
foreach (System.Net.Sockets.Socket ser in st)
{
random.NextBytes(array);
try
{
ser.BeginSend(array, 0, array.Length, SocketFlags.None, (AsyncCallback)delegate(IAsyncResult ar)
{
try
{
ser.EndSend(ar);
}
catch (Exception)
{
iDissconnected(ser);
}
}, null);
}
catch (Exception)
{
iDissconnected(ser);
}
}
}
System.Threading.Thread.Sleep(1);
}
Program._Server.Close();
}
internal static void iDissconnected(System.Net.Sockets.Socket client)
{
lock (ConnectedClients)
for (int i = 0; i < ConnectedClients.Count; i++)
if (ConnectedClients[i].Equals(client))
{
ConnectedClients.RemoveAt(i);
i--;
}
}
}
Client:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter IP Address: ");
string Address = Console.ReadLine();
Console.WriteLine();
ushort Port = 8081;
System.Net.Sockets.Socket Client;
Client = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(Address, (int)Port);
Console.WriteLine("Connected");
int p = 0;
int t = Environment.TickCount;
while (true)
{
if (Client.Available > 0)
{
byte[] z = new byte[1024];
int r = Client.Receive(z); ;
p += r;
}
else
{
System.Threading.Thread.Sleep(10);
}
if (Environment.TickCount - t >= 1000)
{
t = Environment.TickCount;
Console.WriteLine(Program.FormatFileSizeAsString(p) + " Readed,");
p = 0;
}
}
}
public static string FormatFileSizeAsString(int len)
{
if (len < 750 && len > 0)
return "0.0 B ~";
string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
int i;
double dblSByte = len;
for (i = 0; (int)(len / 1024) > 0; i++, len /= 1024)
dblSByte = len / 1024.0;
return String.Format("{0:0.0} {1}", dblSByte, Suffix[i]);
}
}
Thanks all, Please tell me what you think about possible problems.
It was some sort of limitation by ISP per each connection.
Solving was funny. I used to send a HTTP Header before my request and ISP increased my speed because of that.