I'm creating a cross platform application that uses Artnet and UDP protocol to communicate with a device on the network. I know Artnet is also UDP.
Where it works:
Windows OS:
Ethernet. Direct Link and Router controlled.
Wifi. Direct Link and Router Controlled.
Android OS:
Ethernet. N/A
Wifi. Direct Link only.
iOS:
Ethernet. N/A
Wifi. Direct Link only.
Don't understand why there's 0 communication when there's a router involved on Android and iOS. I tried all the suggested codes I could find online and ticked all the capabilities that I could find for Android and iOS.
Wireshark shows there is transmission going on, but my App doesn't capture the packets.
Snipets:
var artnet = new ArtNetSocket(); // using System.Net.Sockets;
artnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
artnet.Bind(new IPEndPoint(LocalIP, 6454));
artnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
EndPoint localPort = new IPEndPoint(IPAddress.Any, Port);
ArtNetData data= new ArtNetData();
artnet.BeginReceiveFrom(recieveState.buffer, 0, recieveState.bufferSize, SocketFlags.None, ref localPort, new AsyncCallback(WhenRecieved), data);
private void WhenRecieved(IAsyncResult state)
{
//1.Do something when received
//2.Begin receive again
}
How I look for IPs:
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in Interfaces)
{
if (Interface.NetworkInterfaceType != NetworkInterfaceType.Loopback )
{
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (var info in UnicastIPInfoCol)
{
if (info.Address.AddressFamily == AddressFamily.InterNetwork)
{
IPsets.Add(new IPCouples(info.Address, info.IPv4Mask));
}
}
}
}
It's so weird it's probably something simple...
Ok, because I was creating sockets for each IP group, packets weren't captured on public networks, unless the APP was on a Microsoft OS device. If I create a UDPClient and bind it to a port, instead of the localIP address, it will capture everything coming on that port, regardless of the sender's IP Address. If you check the IP address of the socket, it will be 0.0.0.0:PortNumber.
public class Something: UdpClient
{
public int LocalPort;
public Something(int LocalPort) : base(LocalPort)
{
EnableBroadcast = true;
this.LocalPort = LocalPort;
StartListening();
}
private void StartListening()
{
//IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
StateObject state = new StateObject();
state.workSocket = Client;
BeginReceive(received, state);
}
catch (SocketException e)
{
Console.WriteLine(e);
}
}
private void received(IAsyncResult ar)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
StateObject state = (StateObject)ar.AsyncState;
var message = EndReceive(ar, ref remoteEndPoint);
if (message.Length > 0)
{
var messageString = (Encoding.UTF8.GetString(message));
//Do Something
}
StartListening();
}
public SendToAll(string message)
{
var callMessage = Encoding.ASCII.GetBytes(message);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
if (UnicatIPInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
EnableBroadcast = true;
Send(callMessage, callMessage.Length, new IPEndPoint(GetBroadcast(UnicatIPInfo.Address,UnicatIPInfo.IPv4Mask) , LocalPort));
}
}
}
private IPAddress GetBroadcast(IPAddress someAddress, IPAddress someMask)
{
//Do something to get broadscat
return Broadcast;
}
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
It works on all platform. Carefull which port you use.
Related
I have a sample Socket application that communicates between two devices using and IP address and port. The IPV4 IP-addresses work fine in the application but I cannot seem to get the correct information for the IPV6 IP-addresses.
I believe I understand what is being talked about in this article with regarding to the Zone ID for an IPV6 address
https://howdoesinternetwork.com/2013/ipv6-zone-id
and I also believe I understand what is being said here within that document:
If you want to ping a neighbor computer, you will need to specify the neighbor’s IPv6 Link-Local address plus the Zone ID of your computer’s network adapter that is going towards that computer.
i.e. I need to use the remote IPV6 address with the local device's Zone ID.
My problem is I cannot seem to figure out what the local device's (ios, android) Zone ID is for IPV6 addresses. I have uploaded my sample Xamarin Forms socket server and client code to GitHub and it can be accessed here.
Server Code: https://github.com/gceaser/AsyncSocket
Client Code: https://github.com/gceaser/AsyncSocketClient
I have the IP Addresses and ports defined in the App.xaml.cs for each project and a switch in each project to go back and forth between an IP V4 and V6 connection. (You should update the IP Addresses for your environment if you are trying to test this.) The V4 connection works but I cannot get the V6 connection to work. Any help would be greatly appreciated.
NOTE: To the best of my knowledge you cannot run the client and server on the same windows machine. Something weird about sockets not being able to communicate that way as I have document in one of my other StackOverflow post. Thus to test please run the server on a Windows box and the Client within iOS.
UPDATE:
Here is the code for the Server Socket connection:
using System;
using
System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Collections.Generic;
namespace AsyncSocketServer
{
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public delegate void onMessageReceivedComplete(object sender, string message);
public delegate void onResponseMessageSent(object sender, string message);
public static event onMessageReceivedComplete MessageReceivedComplete;
public static event onResponseMessageSent ResponseMessageSent;
public AsynchronousSocketListener()
{
}
public async static Task StartListening(IPAddress pobj_IPAddress, int pi_Port)
{
try
{
//IPAddress ipAddress = IPAddress.Parse(pobj_IPAddress);
IPEndPoint localEndPoint = new IPEndPoint(pobj_IPAddress, pi_Port);
Socket listener = new Socket(pobj_IPAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(100);
//ViewModelObjects.AppSettings.SocketStatus = ge_SocketStatus.e_Listening;
await Task.Delay(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Debug.WriteLine("Waiting for a connection on " + pobj_IPAddress + " at port " + pi_Port.ToString() + "...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Debug.WriteLine("StartListening Error" + e.ToString());
}
Debug.WriteLine("Read To end class");
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
//If we have shut down the socket dont do this.
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
Debug.WriteLine("AcceptCallback Error" + e.ToString());
}
}
public static void ReadCallback(IAsyncResult ar)
{
try
{
string ls_ReceivedCommunicationContent = string.Empty;
string ls_ReturnCommunicationContent = string.Empty;
//string content = string.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
ls_ReceivedCommunicationContent = state.sb.ToString();
if (ls_ReceivedCommunicationContent.IndexOf("<EOF>") > -1)
{
//We need to take off the end of file marker
string ls_WorkContent = ls_ReceivedCommunicationContent.Replace("<EOF>", "");
ls_ReturnCommunicationContent = ls_WorkContent;
//Different than app
Device.BeginInvokeOnMainThread(() => {
MessageReceivedComplete(null, ls_WorkContent);
});
Send(handler, ls_ReturnCommunicationContent);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
catch (Exception e)
{
Debug.WriteLine("ReadCallback Error" + e.ToString());
}
}
private static void Send(Socket handler, String data)
{
try
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
Device.BeginInvokeOnMainThread(() => {
ResponseMessageSent(null, data);
});
}
catch (Exception e)
{
Debug.WriteLine("Send Error" + e.ToString());
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Debug.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Debug.WriteLine("SendCallback Error" + e.ToString());
}
}
}
}
Here is the client Code:
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace AsyncSocketClient
{
// This template use base socket syntax to change Pattern. (like Send, Receive, and so on)
// Convert to Task-based Asynchronous Pattern. (TAP)
public static class AsynchronousClientSocket
{
public static async Task<string> SendMessage(string ps_IPAddress, int pi_Port, string ps_Message)
{
string ls_response = "";
try
{
string ls_ReturnMessage = "";
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
var client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
var isConnect = await client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
if (!isConnect)
{
Console.WriteLine("Can not connect.");
return ls_ReturnMessage;
}
// Send test data to the remote device.
var bytesSent = await client.SendAsync(ps_Message + "<EOF>").ConfigureAwait(false);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Receive the response from the remote device.
ls_response = await client.ReceiveAsync().ConfigureAwait(false);
// Write the response to the console.
Console.WriteLine("Response received : {0}", ls_response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return ls_response;
}
private static Task<bool> ConnectAsync(this Socket client, IPEndPoint remoteEndPoint)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (remoteEndPoint == null) throw new ArgumentNullException(nameof(remoteEndPoint));
return Task.Run(() => Connect(client, remoteEndPoint));
}
private static bool Connect(this Socket client, EndPoint remoteEndPoint)
{
if (client == null || remoteEndPoint == null)
return false;
try
{
client.Connect(remoteEndPoint);
return true;
}
catch (Exception)
{
return false;
}
}
private static async Task<string> ReceiveAsync(this Socket client, int waitForFirstDelaySeconds = 3)
{
if (client == null) throw new ArgumentNullException(nameof(client));
// Timeout for wait to receive and prepare data.
for (var i = 0; i < waitForFirstDelaySeconds; i++)
{
if (client.Available > 0)
break;
await Task.Delay(1000).ConfigureAwait(false);
}
// return null If data is not available.
if (client.Available < 1)
return null;
// Size of receive buffer.
const int bufferSize = 1024;
var buffer = new byte[bufferSize];
// Get data
var response = new StringBuilder(bufferSize);
do
{
var size = Math.Min(bufferSize, client.Available);
await Task.Run(() => client.Receive(buffer)).ConfigureAwait(false);
response.Append(Encoding.ASCII.GetString(buffer, 0, size));
} while (client.Available > 0);
// Return result.
return response.ToString();
}
private static async Task<int> SendAsync(this Socket client, string data)
{
var byteData = Encoding.ASCII.GetBytes(data);
return await SendAsync(client, byteData, 0, byteData.Length, 0).ConfigureAwait(false);
}
private static Task<int> SendAsync(this Socket client, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (client == null) throw new ArgumentNullException(nameof(client));
return Task.Run(() => client.Send(buffer, offset, size, socketFlags));
}
}
}
When I start the serer, switch it to IPV6 and start it, I get the message that it is waiting for a connection as follows:
Waiting for a connection on fe80::cda4:ea52:29f5:2c7c at port 8080...
When I start the Client, switch it to IPV6 and attempt to send a message, I get the error:
2020-06-19 09:32:51.029902-0400 AsyncSocketClient.iOS[33593:9360848] Can not connect.
i made a Async Server Socket Code using C# Socket.
Although i wrote a code, then test to Console Environment,
it was working, but i tested that code at UWP.
but, it was not working. cannot accepts client.
Bind, Listen, Accept there are all no error, but this socket code cannot accepts client!
how can i solve me?? please help me..
private Socket m_ServerSocket;
private List<Socket> m_ClientSocket;
private int m_iPort = 1123;
private int m_iClients = 8;
private int m_iBufferSize = 128;
public bool Open(int IN_iPort, int IN_iClients, int IN_iBufferSize)
{
try
{
m_iPort = IN_iPort;
m_iClients = IN_iClients;
m_iBufferSize = IN_iBufferSize;
m_ClientSocket = new List<Socket>();
m_ServerSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_iPort);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(m_iClients);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
}
catch (Exception e)
{
return false;
}
m_bIsOpen = true;
return true;
}
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
m_ClientSocket.Add(ClientSocket);
if (m_ClientSocket != null)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[m_iBufferSize];
args.SetBuffer(szData, 0, m_iBufferSize);
args.UserToken = m_ClientSocket;
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
}
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
I have check your code, there seems no issue existing in your code. Please check if you have checked Internet(Clent&Server)option in your project appxmanifest. For more detail you could refer to Sockets official documentation.
i've faceing a weird problem i wrote a c# simple chat app and it works perfect when i launch the 2 clients on 1 machine but when i try one on my laptop(other computer but same ip) or send it to my friend it's just not working... we both turned off the firewall
thats the server code(part of it which i think can be the problem)
private void StartListening()
{
listener = new TcpListener(IPAddress.Any, listenport);
listener.Start();
while (true) {
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
//listener.Stop();
}
and that's the client code
private void EstablishConnection()
{
statusBar1.Text = "Connecting to Server";
try
{
clientsocket = new TcpClient("10.0.0.3",serverport);
ns = clientsocket.GetStream();
sr = new StreamReader(ns);
connected = true;
}
catch (Exception e)
{
MessageBox.Show("Could not connect to Server","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
statusBar1.Text = "Disconnected";
}
}
private void RegisterWithServer()
{
try
{
string command = "CONN|" + ChatOut.Text;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
string serverresponse = sr.ReadLine();
serverresponse.Trim();
string[] tokens = serverresponse.Split(new Char[]{'|'});
if(tokens[0] == "LIST")
{
statusBar1.Text = "Connected";
btnDisconnect.Enabled = true;
}
for(int n=1; n<tokens.Length-1; n++)
lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'}));
this.Text = clientname + ": Connected to Chat Server";
}
catch (Exception e)
{
MessageBox.Show("Error Registering","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ReceiveChat()
{
bool keepalive = true;
while (keepalive)
{
try
{
Byte[] buffer = new Byte[2048];
ns.Read(buffer,0,buffer.Length);
string chatter = System.Text.Encoding.ASCII.GetString(buffer);
string[] tokens = chatter.Split(new Char[]{'|'});
if (tokens[0] == "CHAT")
{
rtbChatIn.AppendText(tokens[1]);
if(logging)
logwriter.WriteLine(tokens[1]);
}
if (tokens[0] == "PRIV") {
rtbChatIn.AppendText("Private from ");
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(tokens[2] + "\r\n");
if(logging){
logwriter.Write("Private from ");
logwriter.Write(tokens[1].Trim() );
logwriter.WriteLine(tokens[2] + "\r\n");
}
}
if (tokens[0] == "JOIN")
{
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(" has joined the Chat\r\n");
if(logging){
logwriter.WriteLine(tokens[1]+" has joined the Chat");
}
string newguy = tokens[1].Trim(new char[]{'\r','\n'});
lbChatters.Items.Add(newguy);
}
if (tokens[0] == "GONE")
{
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(" has left the Chat\r\n");
if(logging){
logwriter.WriteLine(tokens[1]+" has left the Chat");
}
lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'}));
}
if (tokens[0] == "QUIT")
{
ns.Close();
clientsocket.Close();
keepalive = false;
statusBar1.Text = "Server has stopped";
connected= false;
btnSend.Enabled = false;
btnDisconnect.Enabled = false;
}
}
catch(Exception e){}
}
}
private void QuitChat()
{
if(connected) {
try{
string command = "GONE|" + clientname;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
clientsocket.Close();
}
catch(Exception ex){
}
}
if(logging)
logwriter.Close();
if(receive != null && receive.IsAlive)
receive.Abort();
this.Text = "ChatClient";
}
private void StartStopLogging()
{
if(!logging){
if(!Directory.Exists("logs"))
Directory.CreateDirectory("logs");
string fname = "logs\\" + DateTime.Now.ToString("ddMMyyHHmm") + ".txt";
logwriter = new StreamWriter(new FileStream(fname, FileMode.OpenOrCreate,
FileAccess.Write));
logging = true;
btnLog.Text = "Stop Logging";
statusBar1.Text = "Connected - Log on";
}
else{
logwriter.Close();
logging = false;
btnLog.Text = "Start Logging";
statusBar1.Text = "Connected - Log off";
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(String[] args)
{
ChatClientForm cf = new ChatClientForm();
if(args.Length == 0)
cf.serveraddress = "localhost";
else
cf.serveraddress = args[0];
Application.Run(cf);
}
private void btnConnect_Click(object sender, System.EventArgs e)
{
if(ChatOut.Text == ""){
MessageBox.Show("Enter a name in the box before connecting","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else
clientname = ChatOut.Text;
EstablishConnection();
if(connected)
{
RegisterWithServer();
receive = new Thread(new ThreadStart(ReceiveChat));
receive.Start();
btnSend.Enabled = true;
btnConnect.Enabled = false;
ChatOut.Text = "";
}
im breaking my head over 2 weeks with that... please someone help... :(
basically you have a device on your network (It is probably 10.0.01 or 10.0.0.254, but it could be something else). This is probably either your router / cablemodem / dsl modem. This allows you to do Network Address Translation / Port Address Translation (NAT/PAT). Which allows you to share 1 Public /WAN IP address (79.181.175.247) with all of the computers on your LAN (10.0.0.*). It does this by remapping all of your connections outbound to share the one address, and it keeps track of all of these connections. So when your computer goes out to connect to the internet (say browse a website). It connects from from 10.0.0.3 port 45356 to say google.com port 80. The firewall then maps the request to come from 79.181.175.247 port 5634 and sends the packet to google, and keeps track that return traffic to port 5634 maps to 10.0.0.3 port 45356, so it sends it back to the requesting host.
A side effect is that inbound connections don't know where to go. So for example if your serverport is 1234 on your chat program,and it is listening on 0.0.0.0 of your laptop (10.0.0.3). Your Firewall/Router (10.0.0.1?) doesn't know about this port (there are mechanisms, such as UPNP to communicate this up to compatible routers, but that is outside the scope of this). So you need to manually tell your router/firewall that any connections on the public IP address on port 1234 should be forwarded to port 1234 on your laptop. Depending upon the firewall/router this can have different names. Could be Port Forward, or could be called a mapping, etc... This is required so that the inbound traffic makes it directly to your program.
If you where to try this on your local lan (With firewalls disabled on your computer), you would need to use your internal IP addresses (10.0.0.x) to connect between laptop and other computer (you said same IP, but internally they need to have different addresses, or else they won't work).
I trying to write program, that combines several machines in ring. And after that I send token around this ring. I have a problem: when marker has passed around the ring once and I want to send it second time, machine doesn't want to accept it marker. Sometimes VS rises exception, sort of "... host forcibly closed the connection". Before this problem did not arise at work with asynchronous sockets...
I guess, that problem in listening socket, that work out 1 time and closed. But how can I fix it?
Thanks in advance for your help.
Function, that initializes machines:
private void connectButton_Click(object sender, EventArgs e)
{
if (!connected)
{
//some operation
}
else
{
//some operation
}
try
{
sendS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
recieveS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
portFrom = int.Parse(port1TextBox.Text);
portTo = int.Parse(port2TextBox.Text);
}
catch (Exception)
{
port1TextBox.Text = "Incorrect!";
}
IPAddress ipAddressFrom = IPAddress.Parse("192.168.1.122");
IPEndPoint ipEnd = new IPEndPoint(ipAddressFrom, portFrom); //IPAddress.Any
sendS.Bind(ipEnd);
sendS.Listen(1);
sendS.BeginAccept(new AsyncCallback(accept), null);
}
public void accept(IAsyncResult asyn)
{
Socket sock = sendS.EndAccept(asyn);
// Let the worker Socket do the further processing for the just connected client
begin(sock);
// Since the main Socket is now free, it can go back and wait for
// other clients who are attempting to connect
sendS.BeginAccept(new AsyncCallback(accept), null);
}
public class SocketPacket
{
public Socket m_currentSocket;
public byte[] dataBuffer;
// Constructor that takes one argument.
public SocketPacket(int size)
{
dataBuffer = new byte[size];
}
}
public void begin(Socket s)
{
AsyncCallback pfnWorkerCallBack = new AsyncCallback(serialPort1_DataReceived);
SocketPacket theSocPkt = new SocketPacket(15);
theSocPkt.m_currentSocket = s;
s.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
private void serialPort1_DataReceived(IAsyncResult asyn)
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = socketData.m_currentSocket.EndReceive(asyn);
byte[] dataBytes = socketData.dataBuffer.ToArray();
for (int i = dataBytes.Length - 1; i > 0; i--)
{
if (dataBytes[i] != 0)
{
Array.Resize(ref dataBytes, i+1);
break;
}
}
Encoding enc = Encoding.GetEncoding(1251);
String text = enc.GetString(dataBytes);
analyze(text);
}
Function, that connects 2 machines:
private void button1_Click(object sender, EventArgs e)
{
if (connected)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipTo.Text), System.Convert.ToInt32(portTo));
recieveS.Connect(ip);
}
}
Ok. Solved. I forgot about string
begin(socketData.m_currentSocket);
at the end serialPort1_DataReceived function...
I wrote a udp send and receive unity3d plugin dll in c#, but it cannot receive any udp packets from server on iphone4s.
When server send a udp packet to the demo running on iphone4s, it cannot receive anything.
When server send a udp packet to the demo running on ipod touch 4, it works!Received the packet!
When server send a udp packet to the demo running in the Unity3d editor, it works ok!
I used Wireshark to capture the packets between client and server, it indeed captured the packet that server sent to the demo, but the client demo seems doesn't receive anythig.
Why?
internal class RudpNetInteractor
{
private Socket socket;
private EndPoint serverAddress;
internal RudpNetInteractor(IPEndPoint serverAddress)
{
this.rudpClient = rudpClient;
this.serverAddress = serverAddress;
}
internal void BuildConnection()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(serverAddress);
BeginReceive();
}
internal void Send(byte[] buffer)
{
socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
}
private void OnSend(IAsyncResult ar)
{
try
{
socket.EndSend(ar);
}
catch {}
}
internal void Destroy()
{
socket.Close();
socket = null;
}
private void OnReceive(IAsyncResult ar)
{
try
{
SocketReceiveInfo receiveInfo = (SocketReceiveInfo)ar.AsyncState;
Socket receiveSocket = receiveInfo.ReceiveSocket;
int len = receiveSocket.EndReceive(ar);
if (len > 0)
{
byte[] dest = new byte[len];
Array.Copy(receiveInfo.ReceiveBytes, dest, len);
Console.WriteLine(BitConverter.ToString(dest));
}
BeginReceive();
}
catch {}
}
private void BeginReceive()
{
byte[] receiveBytes = new byte[576];
SocketReceiveInfo info = new SocketReceiveInfo(receiveBytes, socket);
socket.BeginReceiveFrom(receiveBytes, 0, receiveBytes.Length, SocketFlags.None, ref serverAddress, new AsyncCallback(OnReceive), info);
}
}
internal class SocketReceiveInfo
{
private byte[] receiveBytes;
private Socket receiveSocket;
internal SocketReceiveInfo(byte[] receiveBytes, Socket receiveSocket)
{
this.receiveBytes = receiveBytes;
this.receiveSocket = receiveSocket;
}
internal byte[] ReceiveBytes
{
get { return receiveBytes; }
}
internal Socket ReceiveSocket
{
get { return receiveSocket; }
}
}