So I'm new to Unity and need to make a multiplayer game where I could sync clients with the interface on the Game server, I've created a Client and a server and the client do connect to the server but the problem is that it couldn't send messages, all that server receive is Null
I'm running the server as an application and the client need to be a WebGL
This is my Server.cs :
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class server : MonoBehaviour
{
private const int MAX_CONNECTIONS = 2000;
private const string SERVER_IP = "192.168.1.8";
private const int SERVER_PORT = 8999;
private const int SERVER_WEB_PORT = 8998;
private const int BUFFER_SIZE = 400000;
private int reliablechannelid;
private int unreliablechannelid;
private int hostId;
private int webHosted;
private byte[] buffer = new byte[BUFFER_SIZE];
private bool isInit;
// Start is called before the first frame update
void Start()
{
GlobalConfig config = new GlobalConfig();
NetworkTransport.Init(config);
ConnectionConfig cc = new ConnectionConfig();
reliablechannelid = cc.AddChannel(QosType.Reliable);
unreliablechannelid = cc.AddChannel(QosType.Unreliable);
HostTopology topo = new HostTopology(cc, MAX_CONNECTIONS);
hostId = NetworkTransport.AddHost(topo, SERVER_PORT);
webHosted = NetworkTransport.AddWebsocketHost(topo, SERVER_WEB_PORT);
isInit = true;
}
//This function is called when data is sent
void OnData(int hostId, int connectionId, int channelId, byte[] data, int size, NetworkError error)
{
//Here the message being received is deserialized and output to the console
Stream serializedMessage = new MemoryStream(data);
BinaryFormatter formatter = new BinaryFormatter();
string message = formatter.Deserialize(serializedMessage).ToString();
//Output the deserialized message as well as the connection information to the console
Debug.Log("OnData(hostId = " + hostId + ", connectionId = "
+ connectionId + ", channelId = " + channelId + ", data = "
+ message + ", size = " + size + ", error = " + error.ToString() + ")");
Debug.Log("data = " + message);
}
// Update is called once per frame
void Update()
{
{
if (!isInit)
{
return;
}
int outHostId;
int outConnectionId;
int outChannelId;
byte[] buffer = new byte[1024];
int receivedSize;
byte error;
//Set up the Network Transport to receive the incoming message, and decide what type of event
NetworkEventType eventType = NetworkTransport.Receive(out outHostId, out outConnectionId, out outChannelId, buffer, buffer.Length, out receivedSize, out error);
switch (eventType)
{
//Use this case when there is a connection detected
case NetworkEventType.ConnectEvent:
{
//Call the function to deal with the received information
Debug.Log("Connected");
break;
}
//This case is called if the event type is a data event, like the serialized message
case NetworkEventType.DataEvent:
{
//Call the function to deal with the received data
OnData(outHostId, outConnectionId, outChannelId, buffer, receivedSize, (NetworkError)error);
break;
}
case NetworkEventType.Nothing:
break;
default:
//Output the error
Debug.LogError("Unknown network message type received: " + eventType);
break;
}
}
}
}
This is my Client.cs :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine.UI;
using System.IO;
public class client : MonoBehaviour
{
private const int MAX_CONNECTIONS = 2000;
private const string SERVER_IP = "192.168.1.7";
private const int SERVER_PORT = 8999;
private const int SERVER_WEB_PORT = 8998;
private const int BUFFER_SIZE = 400000;
private int connectionId;
private int reliablechannelid;
private int unreliableChannelId;
private int hostId;
bool ok;
private byte error;
// private byte[] buffer = new byte[BUFFER_SIZE];
private bool isConnected;
public string Msg = "test";
public byte[] buffer;
// Start is called before the first frame update
void Connect()
{
GlobalConfig config = new GlobalConfig();
NetworkTransport.Init(config);
ConnectionConfig cc = new ConnectionConfig();
reliablechannelid = cc.AddChannel(QosType.Reliable);
HostTopology topo = new HostTopology(cc, MAX_CONNECTIONS);
hostId = NetworkTransport.AddHost(topo, 0);
#if UNITY_WEBGL
connectionId = NetworkTransport.Connect(hostId, SERVER_IP, SERVER_WEB_PORT, 0, out error);
Debug.Log((NetworkError)error);
Debug.Log("connectionId= "+connectionId);
#else
connectionId = NetworkTransport.Connect(hostId, SERVER_IP, SERVER_PORT, 0, out error);
Debug.Log((NetworkError)error);
Debug.Log("connectionId= " + connectionId);
#endif
}
//This is the function that serializes the message before sending it
void SendMyMessage(string textInput)
{
byte error;
byte[] buffer = new byte[1024];
Stream message = new MemoryStream(buffer);
BinaryFormatter formatter = new BinaryFormatter();
//Serialize the message
formatter.Serialize(message, textInput);
//Send the message from the "client" with the serialized message and the connection information
NetworkTransport.Send(hostId, connectionId, reliablechannelid, buffer, (int)message.Position, out error);
//If there is an error, output message error to the console
if ((NetworkError)error != NetworkError.Ok)
{
Debug.Log("Message send error: " + (NetworkError)error);
}
}
// Update is called once per frame
void Update()
{
SendMyMessage("heyyyyy");
}
}
I have found the solution ,
i just added
NetworkTransport.Connect(hostId, SERVER_IP, SERVER_WEB_PORT, 0, out error);
to my server too , i didn't know that server need to be connected too
hope this will help someone
Related
I have a problem in my code with receiving data. How to make unity receive data all the time?I only manage to log in with my code.The server sends information at different times. Can't the client see them?The "HandleResponse" function should go to default:.Am I wrongly programmed to receive data?I tried another way to receive data. How to solve the problem so that the client listens all the time or the server does not send something?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
public class LogRegSerw : MonoBehaviour
{
public GameObject gameStartPanel;
GameObject gOPlayer;
public InputField loginInputField;
public InputField passwordInputField;
public InputField loginI;
public InputField passwordI;
private TcpClient client;
List<Player> players = new List<Player>();
class Player
{
public string login;
public Vector2 position;
public Player(string login, Vector2 position)
{
this.login = login;
this.position = position;
}
}
void Start()
{
client = new TcpClient();
client.Connect("localhost", 1234);
Debug.Log("Connected to server");
gOPlayer = GameObject.Find("player");
}
private void SendMyPosition()
{
float x = gOPlayer.transform.position.x;
float y = gOPlayer.transform.position.y;
float z = gOPlayer.transform.rotation.eulerAngles.z;
SendDate("player "+ loginI.text +" "+x+" "+y+" "+z);
}
public void Register()
{
string login = loginInputField.text;
string password = passwordInputField.text;
SendDate("register " + login + " " + password);
Debug.Log("Rejestracja");
}
public void Login()
{
string login = loginI.text;
string password = passwordI.text;
SendDate("login " + login + " " + password);
//ReceiveData();
StartCoroutine(ReceiveData());
}
private void SendDate(string message)
{
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(message);
writer.Flush();
}
/*private void ReceiveData()
{
NetworkStream stream = client.GetStream();
byte[] data = new byte[256];
int bytes = stream.Read(data, 0, data.Length);
string response = Encoding.ASCII.GetString(data, 0, bytes);
HandleResponse(response);
}*/
private IEnumerator ReceiveData()
{
NetworkStream stream = client.GetStream();
byte[] data = new byte[256];
int bytes = stream.Read(data, 0, data.Length);
if (bytes > 0)
{
string response = Encoding.ASCII.GetString(data, 0, bytes);
HandleResponse(response);
}
else
{
yield return new WaitForSeconds(0.1f);
StartCoroutine(ReceiveData());
}
}
private void HandleResponse(string response)
{
string[] command = response.Split(' ');
switch (command[0])
{
case "Success":
Debug.Log(command[1]+" "+command[2]+" "+command[3]);
float xx = float.Parse(command[2]);
float yy = float.Parse(command[3]);
LoginSucc(command[1], xx, yy);
break;
case "Invalid":
Debug.Log("Invalid login or password");
break;
case "List":
Debug.Log("Lista...");
break;
default:
Debug.Log("Cos nie tak Linia 75: " + response);
break;
}
}
private void LoginSucc(string name, float x, float y) /////////////////////
{
Vector3 temp = new Vector3(x ,y, 0);
gOPlayer.transform.position += temp;
gOPlayer.GetComponent<PlayerMov>().zalogowany = true ;
gameStartPanel.gameObject.SetActive(false);
}
void Update()
{
if (Input.GetKeyDown("up")|| Input.GetKeyDown("down")|| Input.GetKeyDown("left")|| Input.GetKeyDown("right"))
{
SendMyPosition();
}
}
}
So I am creating UNet multiplayer application but i came to a problem while receiving message.
Application is for android but I also built it for computer.
When I run Server through unity editor and connect to it with client from computer I have part of code to test connection and send message and it is working and send message when player connects.
When I connect with phone it doesn't send message.
What I know is on phone it return NetworkTransport.Connect() value as 1 which means that it connected, but I do not think it connected it and i will explain it after code.
Here is my server code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
public class Server : MonoBehaviour
{
private const int MAX_CONNECTION = 100;
private int port = 7777;
private int hostId;
private int webHostId;
private int reliableChannel;
private int unreliableChannel;
private bool isStarted;
private byte error;
private void Start ()
{
NetworkTransport.Init();
ConnectionConfig cc = new ConnectionConfig();
reliableChannel = cc.AddChannel(QosType.Reliable);
unreliableChannel = cc.AddChannel(QosType.Unreliable);
HostTopology topology = new HostTopology(cc, MAX_CONNECTION);
hostId = NetworkTransport.AddHost(topology, port, null);
webHostId = NetworkTransport.AddWebsocketHost(topology, 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:
break;
case NetworkEventType.ConnectEvent:
Debug.Log("Player " + connectionId + " has connected");
break;
case NetworkEventType.DataEvent:
string msg = Encoding.Unicode.GetString(recBuffer, 0, dataSize);
Debug.Log("Player " + connectionId + " has sent: " + msg);
break;
case NetworkEventType.DisconnectEvent:
Debug.Log("Player " + connectionId + " has disconnected");
break;
}
}
}
And here is Client Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Client : MonoBehaviour
{
private const int MAX_CONNECTION = 100;
private int port = 7777;
private int hostId;
private int webHostId;
private int reliableChannel;
private int unreliableChannel;
private int connectionId;
private float connectionTime;
private bool isConnected;
private bool isStarted = false;
private byte error;
private string playerName;
public Text text;
public void Connect()
{
string pName = GameObject.Find("NameInput").GetComponent<InputField>().text;
if(pName == "")
{
Debug.Log("You must enter a name!");
return;
}
playerName = pName;
NetworkTransport.Init();
ConnectionConfig cc = new ConnectionConfig();
reliableChannel = cc.AddChannel(QosType.Reliable);
unreliableChannel = cc.AddChannel(QosType.Unreliable);
HostTopology topology = new HostTopology(cc, MAX_CONNECTION);
hostId = NetworkTransport.AddHost(topology, 0);
connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);
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.Nothing:
break;
case NetworkEventType.ConnectEvent:
break;
case NetworkEventType.DataEvent:
break;
case NetworkEventType.DisconnectEvent:
break;
}
}
}
Here is how i tested application step by step.
For this testing i implemented line which change button text to connectionId which is connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error); and it comes right after that line
Build application as .exe (for pc)
Build and run application as .apk (for android) Run application inside editor (android build) - Server scene (which has server script)
Run application on android and pc as clients - Client scene (which has client script)
Input name and press Connect on PC client - inside unity console pops Player 1 has connected
Input name and press Connect on Android client - nothing happens inside unity but button text changes to 1 (which means it connected)
Again press Connect on PC Client (which add another client) and it should be player 3 since on android connection returned positive but instead it returns Player 2 has connected
I have no idea what is happening. Is there i need to do for android to connect or maybe because i am connecting with wifi (it was working normally with unity Network Manager but now i can not do it with Lower Api)
After performing all those tasks in the comment section, below are the possible reasons why this is not working:
1.NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error);
If you run this on Android, it will try to connect to your Android device instead of your PC. You need to change "127.0.0.1" to the IP of your PC so that your Android device can connect to that.
Once you get that working, consider using NetworkDiscovery to automatically find the IP of the other device then connect to it.
2.Make sure that both devices(Android) and PC are connected to the-same network/Wi-Fi.
3.Firewall
The firewall on your computer can block incoming connections. You need to add Unity Editor or the built exe program if you are running your server from the standalone program into exceptions in the Firewall program so that it will allow incoming connections. Just Google "Allow programs through firewall" and you will find so many ways to do this.
I am currently learning to program a chat room application that uses a server. So far everything works fine if I run the server and multiple instances of the application on a single machine. When I try to run the server on one machine and the actual chat application from another, I get an exception that reads "a connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (Ipaddress)(port)"
Server side code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Text;
using System.Threading;
namespace ChatAppServer
{
class Program
{
public static Hashtable ClientList = new Hashtable();
const int PORT = 321;
string localIp;
static void Main(string[] args)
{
TcpListener sckServer = new TcpListener(PORT);
TcpClient sckClient = default(TcpClient);
int counter = 0;
sckServer.Start();
Console.WriteLine("Chat Server is now Running ....");
counter = 0;
//Parser myParser = new Parser();
while (true)
{
counter = counter + 1;
sckClient = sckServer.AcceptTcpClient();
string clientData = "";
byte[] recieveData = new byte[10025];
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
ClientList.Add(clientData, sckClient);
Broadcast(clientData + " joined the chat", clientData, false);
Console.WriteLine(clientData + " connected to the chat");
handleClient client = new handleClient();
client.ClientStart(sckClient, clientData, ClientList);
}
sckClient.Close();
sckServer.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void Broadcast(string msg, string userName, bool flag)
{
foreach (DictionaryEntry Item in ClientList)
{
TcpClient sckBroadcast;
sckBroadcast = (TcpClient)Item.Value;
NetworkStream broadcastStream = sckBroadcast.GetStream();
Byte[] broadcastData = null;
if (flag == true)
{
broadcastData = Encoding.ASCII.GetBytes(userName + ": " + msg);
}
else
{
broadcastData = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastData, 0, broadcastData.Length);
broadcastStream.Flush();
}
}
public class handleClient
{
TcpClient sckClient;
string clId;
Hashtable ClientList;
public void ClientStart(TcpClient inSckClient, string clientId, Hashtable clist) {
this.sckClient = inSckClient;
this.clId = clientId;
this.ClientList = clist;
Thread ctThread = new Thread(runChat);
ctThread.Start();
}
private void runChat() {
int requestCount = 0;
byte[] recieveData = new byte[10025];
string clientData = "";
string rCount = null;
while ((true))
{
try
{
requestCount += 1;
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
Console.WriteLine(clId + " : " + clientData);
rCount = Convert.ToString(requestCount);
Program.Broadcast(clientData, clId, true);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
}
Chat room application code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Need for the application
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ChatApp
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient sckClient = new System.Net.Sockets.TcpClient();
NetworkStream svrStream = default(NetworkStream);
string recieveData = null;
public Form1()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
recieveData = "Connected to Server";
msg();
int serverPort = Convert.ToInt32(txtServerPort.Text);
sckClient.Connect(txtServerIp.Text, serverPort);
svrStream = sckClient.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtUserName.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
Thread ctThread = new Thread(MessageCallBack);
btnSend.Enabled = true;
btnConnect.Enabled = false;
txtUserName.Enabled = false;
txtServerIp.Enabled = false;
txtServerPort.Enabled = false;
ctThread.Start();
}
private void MessageCallBack()
{
while(true)
{
svrStream = sckClient.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = sckClient.ReceiveBufferSize;
svrStream.Read(inStream, 0, buffSize);
string returnData = System.Text.Encoding.ASCII.GetString(inStream);
recieveData = "" + returnData;
msg();
}
}
//function to display data strings
private void msg()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(msg));
}
else
{
lstMessage.Items.Add(recieveData);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
txtMessage.Text = "";
}
I have two troubles with your code :
Do not use .ReceiveBufferSize value because it's a different value of your byte array length. And you can have an index out of range exception.
You have a problem of concurrency in the server side. More than 1 thread try to access to the ClientList and this collection is not thread-safe.
To resolve this, you can use the lock keyword
private static object _lock = new object();
//...
lock (_lock)
{
ClientList.Add(clientData, sckClient);
}
lock (_lock)
{
Broadcast(clientData + " joined the chat", clientData, false);
}
//...
lock (_lock)
{
Program.Broadcast(clientData, clId, true);
}
As you're a beginner, i would give you some tips.
Try to use the asynchronous network functions (better than raw threads), an example there.
There is a lot of tutorials about safety with severals connections in C# (with some thing else, better, than the lock keyword).
I am trying to create a WPF form using Visual Studio C# that will interact with indicators I create for my trading charts in MultiCharts .Net
I've added a WPF Project to the solution and added the namespace for the indicators. However, I can not figure out how I can manipulate inputs for the indicator object. Any help from someone who works with this program would be much appreciated.
You have to create a local network connection to make this work--I used sockets, but anything in a similar way will support the same goal:
Make a new MC indicator like so:
public class tests_OwnApp : IndicatorObject {
public tests_OwnApp(object _ctx):base(_ctx)
{
PortNumber = 5000;
}
[Input]
public int PortNumber { get; set; }
public static string Symbol;
const string ServerIP = "127.0.0.1";
IPAddress localAdd;
TcpListener listener;
TcpClient client;
NetworkStream nwStrm;
private IPlotObject plot1;
protected override void Create() {
// create variable objects, function objects, plot objects etc.
plot1 = AddPlot(new PlotAttributes("", EPlotShapes.Line, Color.Red));
localAdd = IPAddress.Parse(ServerIP);
client = null;
}
protected override void StartCalc() {
// assign inputs
// establish connection
if (listener == null)
{
listener = new TcpListener(localAdd, PortNumber);
}
listener.Stop();
Thread.Sleep(100);
listener.Start();
}
protected override void CalcBar()
{
// indicator logic
if (Bars.LastBarTime <= Bars.Time[0] + new TimeSpan(2,0,0))
{
Symbol = Bars.Info.Name;
if (client == null || !client.Connected)
client = listener.AcceptTcpClient();
// create network stream
nwStrm = client.GetStream();
// send symbol to app:
Output.WriteLine("sending " + Symbol + " to application");
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(Symbol);
string closingPrice = Convert.ToString(Bars.Close[0]);
string totalMsg = "Sym," + Symbol +
"\nClose[0]," + closingPrice + "\nClose[1]," + Bars.Close[1].ToString();
byte[] bytes2 = ASCIIEncoding.ASCII.GetBytes(totalMsg);
nwStrm.Write(bytes2, 0, bytes2.Length);
}
}
}
In your app (Console App example, extends to WPF):
static void Main(string[] args)
{
const int PortNum = 5000;
const string ServerIP = "127.0.0.1";
DateTime startTime = DateTime.Now;
TcpClient client = new TcpClient(ServerIP, PortNum);
NetworkStream nwStream = client.GetStream();
while (true)
{
if (client.ReceiveBufferSize != 0)
{
nwStream = client.GetStream();
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
string msg = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
Console.WriteLine("received: " + msg);
if (DateTime.Now - new TimeSpan(0, 0, 30) > startTime)
{
break;
}
Thread.Sleep(100);
Console.Write("-ping-");
}
}
Console.ReadLine();
}
Run them both together and you'll find they connect and the info is received.
I used this example to get started, in case my example is not sufficient.
Be sure to include all the necessary namespaces:
using System.Net;
using System.Net.Sockets;
See the documentation I believe chapter three shows you how to work with indicators
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
tcp/ip client server not working over internet
i spent the last week working on a simple windows form application that' s supposed to send a couple of integer numbers from client to server or from server to client. So far i have only managed to make it work for lanns, any idea about how to make it work on the open internet ?
Here' s the code in case you need it (also call me noob but i can' t get how this site handles code, ... does not do what i thought it did so feel free to edit my post in case i fail2format)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client_server_penta
{
public class Client
{
#region Fields
private int turno = 1;
private TcpClient[] clients = new TcpClient[1]; //used to remember the active client
private int CoordinateX, CoordinateY; //coordinates, they are used by the application
#endregion
public Client(string address)
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(address), 3000);
client.Connect(serverEndPoint);
clients[0] = client;
Thread ReadFromServer = new Thread(new ParameterizedThreadStart(this.ReadHandler));
ReadFromServer.Start(client);
}
public void SendData(int a, int b)
{
NetworkStream clientStream = clients[0].GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(a.ToString() + '$' + b.ToString() + '$');
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
public int ReadCoordinateX()
{
return this.CoordinateX;
}
public int ReadCoordinateY()
{
return this.CoordinateY;
}
private void ReadHandler(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] buffer;
int bytesRead;
while (true)
{
buffer = new byte[10];
bytesRead = 0;
try
{
bytesRead = clientStream.Read(buffer, 0, buffer.Length);
}
catch
{
//an uknown error has occurred
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//data received
ASCIIEncoding encoder = new ASCIIEncoding();
OnDataReceived(encoder.GetString(buffer, 0, buffer.Length));
}
tcpClient.Close();
}
private void OnDataReceived(string text)
{
string first_number = "";
string second_number = "";
int index = 0;
while (text[index] != '$')
first_number += text[index++];
index++;
while (text[index] != '$')
second_number += text[index++];
this.CoordinateX = Convert.ToInt32(first_number);
this.CoordinateY = Convert.ToInt32(second_number);
var myForm = Application.OpenForms["Form2"] as Form2;
myForm.Text = "Turno N." + Convert.ToString(this.turno++);
}
}
}
//and here' s the server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client_server_penta
{
public class Server
{
private Thread listenThread;
private int turno = 1;
private TcpListener tcpListener;
private TcpClient[] clients = new TcpClient[1]; //used to remember the active client
private int CoordinateX, CoordinateY; //coordinates, they are used by the application
public Server(int port)
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
public void SendData(int a, int b)
{
NetworkStream clientStream = clients[0].GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(a.ToString()+'$'+b.ToString()+'$');
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
public int ReadCoordinateX()
{
return this.CoordinateX;
}
public int ReadCoordinateY()
{
return this.CoordinateY;
}
private void ListenForClients()
{
this.tcpListener.Start();
TcpClient client = this.tcpListener.AcceptTcpClient();
clients[0] = client;
Thread ReadFromClient = new Thread(new ParameterizedThreadStart(this.ReadHandler));
ReadFromClient.Start(client);
}
private void ReadHandler(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] buffer = new byte[10];
int bytesRead;
while (true)
{
buffer = new byte[10];
bytesRead = 0;
try
{
bytesRead = clientStream.Read(buffer, 0, buffer.Length);
}
catch
{
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//data received
ASCIIEncoding encoder = new ASCIIEncoding();
OnDataReceived(encoder.GetString(buffer, 0, buffer.Length));
}
tcpClient.Close();
}
private void OnDataReceived(string text)
{
string first_number = "";
string second_number = "";
int index = 0;
while (text[index] != '$')
first_number += text[index++];
index++;
while (text[index] != '$')
second_number += text[index++];
this.CoordinateX = Convert.ToInt32(first_number);
this.CoordinateY = Convert.ToInt32(second_number);
var myForm = Application.OpenForms["Form2"] as Form2;
myForm.Text = "Turno N."+Convert.ToString(this.turno++);
}
}
}
Have you opened the 3000 port on your firewall on the two sides ?
Yes of course ^^
If you have routers, don't forget to edit the configurations too.