I'm trying to send some information to a server with Android using Monodroid.
The code is as follows:
public void sendSomething()
{
sock = new TcpClient();
sock.Connect(Dns.GetHostAddresses("a.domain.com"), 7777);
String d;
d = "somedata";
StreamWriter w = new StreamWriter(sock.GetStream());
// StreamReader r = new StreamReader(sock.GetStream());
w.WriteLine(d);
w.Flush();
sock.Close();
}
It works fine if I run the exact same routine in a winforms application, but when linked to a button click in monodroid (running on the android virtual device - I'm using the evaluation version) the server will see the connection but no data is received.
Does anybody have any idea why this could be?
(edited to ammend code)
It could be a server issue. E.g. let's assume that:
a) your winform app running on Windows / MS.NET (and not on Mono / Linux or OSX);
b) your server is Windows-based too and does a ReadLine to read sockets
Then the NewLine between the write (Unix \n) and the read (Windows \r\n\) could explain why the server does not report what's being read.
Can you show us how you're reading the data on the server ? (edit your question)
Related
I am developing an application whose main features are:
A group of friends want to have a game of remote role-playing.
The GM opens the application and starts a server. It opens a winForm.
Clients do the same and connect to the server. The list of connected players is updated on all windows (clients / server)
The GM opens a window on his screen and this is also displayed on all clients.
When he draws on it, the drawing also displays "live" on all client screens.
So far I manage to do everything described above except for the last step: drawing on a panel on the server side does not send the drawing to the clients.
To achieve displaying the opened windows on the client side, I serialized my winforms via a custom class. Here is a portion of code to serialize / deserialize :
public static String Serialise(Control c)
{
XmlTextWriter xmlSerialisedForm = new XmlTextWriter(Application.StartupPath + #"\serialise.xml", System.Text.Encoding.Default);
xmlSerialisedForm.Formatting = Formatting.Indented;
xmlSerialisedForm.WriteStartDocument();
xmlSerialisedForm.WriteStartElement("ChildForm");
// enumerate all controls on the form, and serialise them as appropriate
AddChildControls(xmlSerialisedForm, c);
xmlSerialisedForm.WriteEndElement(); // ChildForm
xmlSerialisedForm.WriteEndDocument();
xmlSerialisedForm.Flush();
xmlSerialisedForm.Close();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Application.StartupPath + #"\serialise.xml");
return xmlDoc.InnerXml;
}
public static void Deserialise(Control c, string XmlFileName) {
XmlDocument xmlSerialisedForm = new XmlDocument();
xmlSerialisedForm.LoadXml(XmlFileName);
XmlNode topLevel = xmlSerialisedForm.ChildNodes[1];
foreach (XmlNode n in topLevel.ChildNodes) {
SetControlProperties((Control)c, n);
}
}
I have read dozen of web articles here and there about NOT deserializing Windows Form BUT is there another way to achieve what I'm aiming ?
How can I send through TCP connection to the connected clients data about what i'm doing live on my screen ?
I'm actually building this app to know more about TCP connections and C# in general and my goal is to reproduce what this software, written in C with QT, is actually doing.
Rolistik site
Rolistik sources
Screenshot of a server and a client with a winform launched by the server and received by the client
Thanks for the incoming help
Leor
I am brand new to Universal Windows Apps (Win 10). I am trying to port a console application over to UWP that acts as a remote testing and administrative console for a custom Windows Service application. I can not seem to find any solid example code to demonstrate where to place a socket listener in the MainPage.xaml.cs file (or wherever it's supposed to go). I have been successful with porting the MSDN example into a method that serializes a PCL model object with Json and sends it to the server. I just can not seem to handle the listener correctly. I don't think that I am using it in the right place, especially when it comes to the async usage. I am having protocol\port usage errors because it's basically saying that it is already open (I just tossed it in the test method). I would like to deserialize the Json response that is received and use it to populate a List. Here is an example of what is working for me for sending.
private async void Pulse(string target)
{
if (target == null || target == string.Empty)
{
greetingOutput.Text = "No Ip specified";
return;
}
else
{
try
{
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
Windows.Networking.HostName serverHost = new Windows.Networking.HostName(target);
await socket.ConnectAsync(serverHost, serverPort);
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
HeartBeatPing heartBeatPing = new HeartBeatPing(GetLocalIp(), target);
string msg = JsonConvert.SerializeObject(heartBeatPing);
await writer.WriteLineAsync(msg);
await writer.FlushAsync();
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
catch (Exception xCeption)
{
greetingOutput.Text += "\n" + xCeption.ToString();
}
}
}
Some of you might notice from the greetingsOutput.text that I have started with the "C# Hello World" example from Microsoft's training site.
I would also like to add that I am not going to be using any HTTP for this because there is going to be some custom encryption and other "things" happening with the Json objects that will require separate ports.
I'm not far enough into my Universal Windows Apps with XAML and C# (Unleashed) books to have even a clue as to what I am doing. I am however well seasoned C# programmer in other platforms such as MVC, Windows Service, Console, and others. I have a solid understand of enterprise class patterns and practices based on my knowledge of "The Gang of Four".
Any help would be greatly appreciated. Thank you.
(https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DatagramSocket)
Here is a sample. There are CPP, js, and cs code in this sample, I've only tested the cs code. Wish this can help you.
I have a problem with some code that uses sockets. I want to connect my script over IPv6 but I receive a SocketException when I run this script in Unity. This code works perfectly as a Console Application Project in MonoDevelop:
using System;
using System.Net;
using System.Net.Sockets;
namespace socketIPv6
{
class MainClass
{
public static void Main (string[] args)
{
Socket s;
s = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse("ff15::2");
s.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(ip));
IPEndPoint ipep = new IPEndPoint(IPAddress.IPv6Any, 26000);
s.Bind(ipep);
while (true) {
byte[] b = new byte[1024];
s.Receive (b);
string str = System.Text.Encoding.ASCII.GetString (b, 0, b.Length);
Console.WriteLine (str.Trim ());
}
}
}
}
But the same code (I only changed "Console.WriteLine()" for "Debug.Log()") doesn't work as a Unity Project. This code breaks with the exception: "SocketException: An address incompatible with the requested protocol was used." Can someone help me? Thanks!
Keep in mind that the version of the Mono framework you're linking against from a console app may be different than Unity's mono framework.
This may partially answer what's going on:
Decompiling Unity\Editor\Data\Mono\lib\mono\2.0\System.dll with ILSpy shows at various places a dependency on
internal static void Socket.CheckProtocolSupport()
which, among one other related check therein, attempts to read from the .NET config file(s) from section system.net/settings. If you look at Unity\Editor\Data\Mono\etc\mono\2.0\machine.config it has system.net/settings/<ipv6 enabled="false"/>.
So either that config file is irrelevant or stale, or it appears Unity specifically has turned off or does not support IPv6 sockets.
Try using the ".Net 2.0 Subset" api compatibility in the player settings. I was running in this same thing and it was because we were using the full ".Net 2.0"
This is the bug report if you're interested: https://fogbugz.unity3d.com/default.asp?804510_c5ei44diq6ktnh1u
First I'm using Visual Studio 2012 with C# and the Pcap.Net Library.
I try to to forward packets which I captured before.
What I try to do:
Spoof ARP-Table of my phone.
Redirect the traffic which normally goes to the gateway to my computer.
Log the packets.
Forward them to the gateway.
What I did:
Spoofing ARP-Table -> works fine.
Redirect traffic to my PC -> works fine (logically).
Log the packets to a dumpfile (.pcap) as shown in the tutorial on this site -> works fine (I can open it and read it with wireshark and it looks good).
Forward the packets to the gateway. -> does not work.
I would like to forward them fluently. So what I did was use the "sendBuffer()" function as shown in the tutorial. So I just read in the .pcap file where all the packet information is saved and try to resend it with this "sendBuffer()" function. And of course I use the same adapter to do it.
When I capture the traffic with wireshark I can see that my packets don't even get sent.
(I'm also not sure if it works at the same time while I capture the data to the file. Because the code which should forward them need to read the packets from the file. Isn't there another way?)
My code to forward the packets from the .pcap file (the IDE doesn't give me any error):
It's approximately my code, I don't have it available cause I'm not at home. But should be right.
IList<LivePacketDevice> devices = LivePacketDevice.AllLocalMachine;
PacketDevice selectedOutputDevice = devices[0];
long capLength = new FileInfo(#"E:\CSharp\Pcap\dumpFile.pcap").Length;
bool isSync = true;
OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(#"E:\CSharp\Pcap\dumpFile.pcap");
using (PacketCommunicator inputCommunicator = selectedInputDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
using (PacketCommunicator outputCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
if (inputCommunicator.DataLink != outputCommunicator.DataLink)
{
tB_Log.Text = tB_Log.Text + Environement.NewLine + "ERROR: Different Datalinks!";
}
using (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
{
Packet packet;
while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
{
sendBuffer.Enqueue(packet);
}
outputCommunicator.Transmit(sendBuffer, isSync);
}
}
}
Thank you very much for helping!
I'm fighting here with System.Printing namespace of .net framework.
And what i always saw as a wired thing in all the tools by MS to manage my printservers is they lack Port and Driver managing functionality.
So I'm stuck here with a piece of code that works:
PrintServer _ps = new PrintServer(PServer,
PrintSystemDesiredAccess.AdministrateServer );
_ps.InstallPrintQueue(QToCreate.Name, QToCreate.Driver,new string [] {"LPT1:"}, "winprint", PrintQueueAttributes.None);
And it does create a Queue for me on remote server, using the driver i specify, but driver should be there on server already which i can live with, but i failed to find a way to create new TCP/IP port on my print server, so installing new print queues this way can be something usable. i don't see why am i allowed to only install new queues with existing ports. kinda fails me. If somebody knows how to create a port along with a queue, i'd like to see how.
gah.. and when there is no hope - do research more
short answer - "you can't add a port using system.printing"
long answer - use wmi
vb sample follows:
Set objWMIService = GetObject("winmgmts:")
Set objNewPort = objWMIService.Get _
("Win32_TCPIPPrinterPort").SpawnInstance_
' Use IP of Printer or Machine sharing printer
objNewPort.Name = "IP_192.168.1.1"
objNewPort.Protocol = 1
objNewPort.HostAddress = "192.168.1.1"
' Enter Port number you would like to use
objNewPort.PortNumber = "9999"
objNewPort.SNMPEnabled = False
objNewPort.Put_