In the IPv6(NAT64) environment,networkStream.BeginRead does't work - c#

The following code works well in IPV4,And,In the IPv6(NAT64) environment,it can connect the server and send message success,It can capture the data from server, But,the callback OnRead never be executed.
It's been bothering me for a long time.
private TcpClient client = null;
private const int MAX_READ = 8192;
private NetworkStream outStream = null;
private byte[] byteBuffer = new byte[MAX_READ];
public void ConnectServerByIP(string ip, int port) {
client = new TcpClient(AddressFamily.InterNetworkV6);
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
client.NoDelay = true;
IPAddress ipAddr = IPAddress.Parse(ip);
try {
client.BeginConnect(ipAddr, port, new AsyncCallback(OnConnect), null);
} catch (Exception e) {
Close(); Debug.LogError(e.Message);
}
}
void OnConnect(IAsyncResult asr) {
outStream = client.GetStream();
client.GetStream ().BeginRead (byteBuffer, 0, MAX_READ,new AsyncCallback(OnRead), null);
NetworkManager.AddEvent(Protocal.Connect, new ByteBuffer());
}
void OnRead(IAsyncResult asr) {
Debug.Log ("Hello~");
}

Related

Receiving data all the time

so made client-server-client tcp/ip app in c# that are supposed to communicate between 2 computers that are in different network.
I have few problems , first of them my server wont start on my public ip sayings its not valid in this context. Second is that I need to press send button twice before it sends data to server ,and then server 2 variations of data, one in bytes, other in char how its supposed to be. And third is how to make clients trying to receive data whole time. Should I have connection between clients have open whole time? I tried using timers to check if there is data to be received from the server.
Server code
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 8080);
TcpClient client = default(TcpClient);
TcpClient client2 = default(TcpClient)
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch(Exception ex)
{
Console.WriteLine("Server failed to start... {0}",ex.ToString());
Console.Read();
}
while (true)
{
client = server.AcceptTcpClient(); /
byte[] receivedBuffer = new byte[1000];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer,0,receivedBuffer.Length);
StringBuilder message = new StringBuilder(); foreach (byte b in receivedBuffer)
{
if (b.Equals(126)
) //proveramo d {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
client2 = server.AcceptTcpClient();
byte[] receivedBuffer2 = new byte[1000];
NetworkStream stream2 = client2.GetStream();
stream2.Read(receivedBuffer2, 0, receivedBuffer2.Length);
StringBuilder message2 = new StringBuilder();
foreach (byte g in receivedBuffer2)
{
if (g.Equals(126))
{
break;
}
else
{
message2.Append(g);
}
}
stream2.Write(receivedBuffer, 0, receivedBuffer.Length);
stream.Write(receivedBuffer2,0,receivedBuffer2.Length);
Console.WriteLine(message2.ToString());
Console.WriteLine(message.ToString());
}
Client code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private int port = 8080;
private void submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("192.168.0.13",port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
long byteCount = Encoding.ASCII.GetByteCount(messagebox_TB.Text + 1); byte[] sentDataBytes = new byte[byteCount];
sentDataBytes = Encoding.ASCII.GetBytes(messagebox_TB.Text + "~");
NetworkStream stream = client.GetStream();
stream.Write(sentDataBytes,0,sentDataBytes.Length);
stream.Close();
client.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
long a = 0;
try
{
TcpClient client = new TcpClient("192.168.0.13", port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
NetworkStream stream = client.GetStream();
byte[] receviedBytes = new byte[100];
stream.Read(receviedBytes, 0, receviedBytes.Length);
StringBuilder
message = new StringBuilder();
foreach (byte b in receviedBytes) {
if (b.Equals(126)
) //proveramo {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
textBox1.Text = message.ToString();
client.Close();
stream.Close();
}
catch
{
a++;
}
}
}

Why is my ReceivedBufferSize huge? Up to 65535 bytes

So I am playing around with the Tcp protocol in C# and figured I would connect to my server.
When I connect to my server it notifies me just fine. but then I go to check the ReceivedBufferSize and it's this receivedBuffer={byte[65536]}
When in reality it only gives back a few bytes.
Why is this happening?
Sending this back to my client doesn't do anything either so I removed that part.
I figured it's because the packet is so big.
This part right here
byte[] receivedBuffer = new byte[client.ReceiveBufferSize];
returns receivedBuffer={byte[65536]}
public partial class MainWindow : Window
{
public static IPAddress remoteAddress = IPAddress.Parse("127.0.0.1");
public TcpListener remoteServer = new TcpListener(remoteAddress, 7777);
public TcpClient client = default(TcpClient);
public MainWindow()
{
InitializeComponent();
}
private void BtnListen_OnClick(object sender, RoutedEventArgs e)
{
if (StartServer())
{
client = remoteServer.AcceptTcpClient();
MessageBox.Show("Connected");
byte[] receivedBuffer = new byte[client.ReceiveBufferSize];
NetworkStream clientStream = client.GetStream();
while (client.Connected)
{
if (client.Connected)
{
if (client.ReceiveBufferSize > 0)
{
receivedBuffer = new byte[100];
clientStream.Read(receivedBuffer, 0, receivedBuffer.Length);
}
}
}
}
}
private bool StartServer()
{
try
{
remoteServer.Start();
MessageBox.Show("Server Started...");
return true;
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
throw;
}
}
}
As you can see here, it's only 15 bytes

How to add multiple clients to a server in c#?

My Client Source Code :
public partial class Form1 : Form
{
string serverip = "localHost";
int port = 160;
public Form1()
{
InitializeComponent();
}
private void Submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(serverip, port);
int byteCount = Encoding.ASCII.GetByteCount(Message.Text);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes(Message.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
stream.Close();
client.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
My server
class Program
{
static void Main(string[] args)
{
IPAddress ip = Dns.GetHostEntry("localHost").AddressList[0];
TcpListener server = new TcpListener(ip, 160);
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("The server has started successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
while (true)
{
client = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach (byte b in receivedBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
Console.WriteLine(msg.ToString() + msg.Length);
}
}
}
Essentially i want make it so i can have multiple clients on the server sending a message from different ip addresses of course. I have been using c# a year now mostly in school and I am above average at best at it.
First time asking question so sorry if its in wrong format

TCP Listener - Not updating a received data

This is my first TCP listener program,
I could receive, parse and display data successfully from another PC.
But can you please check why this listener is not receiving another data ?
I want to update it everytime time when a client sends data. But its not updating once received data.
Here is my code:
public partial class FeederControlMonitor : Form
{
public string Status = string.Empty;
public Thread T = null;
public FeederControlMonitor()
{
InitializeComponent();
}
private void FeederControlMonitor_Load(object sender, EventArgs e)
{
label1.Text = "Server is Running...";
ThreadStart Ts = new ThreadStart(StartReceiving);
T = new Thread(Ts);
T.Start();
}
public void StartReceiving()
{
ReceiveTCP(9100);
}
public void ReceiveTCP(int portN)
{
TcpListener Listener = null;
try
{
Listener = new TcpListener(IPAddress.Any, portN);
Listener.Start();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
Console.WriteLine(ex.Message);
}
try
{
Socket client = Listener.AcceptSocket();
byte[] data = new byte[10000];
int size = client.Receive(data);
while (true)
{
client.Close();
ParseData(System.Text.Encoding.Default.GetString(data));
}
Listener.Stop();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
}
}
public void ParseData(string data)
{
var useFulData = data.Substring(data.IndexOf("F1")).Replace(" ", "");
useFulData = useFulData.Remove(useFulData.IndexOf("<ETX>"));
string[] delimeters = { "<DEL>", "<ESC>" };
var listOfValues = useFulData.Split(delimeters, StringSplitOptions.None).ToList();
int pos = 0;
for (int i = 1; i < listOfValues.Count; i += 2, pos++)
{
listOfValues[pos] = listOfValues[i];
}
listOfValues.RemoveRange(pos, listOfValues.Count - pos);
txtTubeName.Text = listOfValues[0];
txtCID.Text = listOfValues[1];
txtLocation.Text = listOfValues[2];
txtGender.Text = listOfValues[3];
txtAge.Text = listOfValues[4];
}
private void btnExit_Click(object sender, EventArgs e)
{
T.Abort();
this.Close();
}
}
Thanks in advance.
To much to explain where are errors. Here is simple multithread TcpServer.
// Initialize listener.
IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpClient client;
// Bind to address and port.
TcpListener listener = new TcpListener(address, 12345);
// Start listener.
listener.Start();
// In endless cycle accepting incoming connections.
// Actually here must be something like while(_keepWork)
// and on some button code to make _keepWork = false to
// stop listening.
while (true)
{
client = listener.AcceptTcpClient();
// When client connected, starting BgWorker
// use "using" statement to automatically free objects after work.
using (BackgroundWorker bgWorker = new BackgroundWorker())
{
// EventHandler.
bgWorker.DoWork += BgWorker_DoWork;
// Past client as argument.
bgWorker.RunWorkerAsync(client);
}
}
And method to handle connection (Edit: with read data part):
private static void BgWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Get argument as TcpClient.
TcpClient client = e.Argument as TcpClient;
// Get stream from client.
NetworkStream netStream = client.GetStream();
// Input buffer to read from stream.
int inBuffSize = 1024;
byte[] inBuff = new byte[inBuffSize];
// Temporary buffer.
byte[] tempBuff;
// Result data recieved from client.
List<byte> data = new List<byte>();
// Read bytes from client into inputbuffer
int dataSize = netStream.Read(inBuff, 0, inBuffSize);
// If data recieved add to result.
while (dataSize > 0)
{
// Create new buffer.
tempBuff = new byte[dataSize];
// Copy data from inputBuffer to tempBuffer.
Array.Copy(inBuff, tempBuff, dataSize);
// Add to result.
data.AddRange(tempBuff);
// Read once more to check if any data still could be recieved.
dataSize = netStream.Read(inBuff, 0, inBuffSize);
}
}

C# UdpClient Works Over Network But Not Over Internet With Port Forwarding

Ok so i've been developing server/client apps for a program i'm making. It works fine over the local network. I've set port forwarding up and im using my external IP address to communicate with the server app. Everything works fine but when I send the client app to my friends to launch, there is no communication to my server for them. Any suggestions?
Server (Marked out important lines, the rest isnt necessary for solving this)
class ServerListener
{
private string _IPAddress;
private int _Port;
private static UdpState _UdpState;
private static UdpClient _UdpServer;
private IPEndPoint _IpEndpoint;
private static BinaryFormatter _BinaryFormatter;
public ServerListener(string ipAddress, int port)
{
_IPAddress = ipAddress;
_Port = port;
_UdpServer = new UdpClient(_Port);
_IpEndpoint = new IPEndPoint(_IPAddress , 8000);
_BinaryFormatter = new BinaryFormatter();
ThreadPool.SetMaxThreads(50, 50);
_UdpState = new UdpState();
_UdpState.IpEndPoint = _IpEndpoint;
_UdpState.UdpClient = _UdpServer;
_UdpServer.Client.SendTimeout = 100;
_UdpServer.Client.ReceiveTimeout = 100;
}
public void StartListenCycle()
{
FetchData();
}
private static void FetchData()
{
_UdpServer.BeginReceive(new AsyncCallback(ReceiveCallback), _UdpState);
}
private static void ReceiveCallback(IAsyncResult ar)
{
FetchData();
ClientDataRequest dataRequest;
UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).UdpClient;
IPEndPoint endpoint = (IPEndPoint)((UdpState)(ar.AsyncState)).IpEndPoint;
//// ----> This lines important Byte[] receiveBytes = udpClient.EndReceive(ar, ref endpoint);
using (var memStream = new MemoryStream())
{
memStream.Write(receiveBytes, 0, receiveBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
dataRequest = (ClientDataRequest)_BinaryFormatter.Deserialize(memStream);
ThreadPool.QueueUserWorkItem(new WaitCallback(ClientRequestHandler.HandleRequest), dataRequest);
}
using (var memStream = new MemoryStream())
{
GameState gameState = new GameState(true);
SerializedGameState dataPacket = new SerializedGameState();
dataPacket.Players = new PlayerInformation[GameState.Players.Count];
gameState.ClientPlayerObjects.CopyTo(dataPacket.Players, 0);
Serializer.Serialize(memStream, dataPacket);
byte[] responseAsBytes = memStream.ToArray();
try
{
//// ----> This lines important udpClient.Send(responseAsBytes, responseAsBytes.Length, endpoint);
}
catch (Exception e)
{
Console.WriteLine("");
}
}
}
}
Client (same again)
class ClientNetworkConnection
{
private string _IPAddress;
private int _Port;
UdpClient _UdpClient;
IPEndPoint _IpEndpoint;
public ClientNetworkConnection(string ipAddress, int port)
{
_IPAddress = ipAddress;
_Port = port;
_UdpClient = new UdpClient();
_UdpClient.Ttl = 10;
_UdpClient.AllowNatTraversal(true);
_IpEndpoint = new IPEndPoint(IPAddress.Parse(_IPAddress), _Port);
_UdpClient.Client.SendTimeout = 100;
_UdpClient.Client.ReceiveTimeout = 100;
_UdpClient.Connect(_IpEndpoint);
}
public void FetchData()
{
while (Thread.CurrentThread.IsAlive)
{
ClientDataRequest request = new ClientDataRequest();
request.PlayerID = DataStore.PlayerId;
request.PlayerName = DataStore.PlayerName;
request.PlayerClicked = DataStore.MouseDown;
request.ClickPosition = new Point(DataStore.MousePositionX, DataStore.MousePositionY);
SerializedGameState response = new SerializedGameState();
byte[] objectAsBytes;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, request);
objectAsBytes = ms.ToArray();
}
/////// -------> Important networky stuff _UdpClient.Send(objectAsBytes, objectAsBytes.Length);
try
{
/////// -------> Important networky stuff var data = _UdpClient.Receive(ref _IpEndpoint);
using (var memStream = new MemoryStream())
{
memStream.Write(data, 0, data.Length);
memStream.Seek(0, SeekOrigin.Begin);
response = Serializer.Deserialize<SerializedGameState>(memStream);
GameState.SetClientStaticVariables(response);
}
}
catch (SocketException e)
{
//Handle Socket exception
}
}
}
}

Categories