I never saw someone commenting this. How should I program when using sockets?
For example, comparing web service and sockets, using web services I can create methods with a clarified name. How can I do this using sockets? What if I want to have "methods" in different classes? How do I organize them?
I am trying to make a game. What if I need to have 300 methods and I need to use sockets?
What about this?
udpClient.Connect("localhost", 15000);
Byte[] sendBytes = Encoding.ASCII.GetBytes("MyClass MyMethod(firstParameter");
udpClient.Send(sendBytes, sendBytes.Length);
I need to pass a string to an UDP communication. How can I organize this in the server side?
How can I split in classes and methods? Or do I need to put 300 "if" in the server side like this?
if(message.Contains("MyClass MyMethod"))
{
MyClass.MyMethod();
}
if(message.Contains("MyClass MyMethod2"))
...
if(message.Contains("MyClass MyMethod3"))
...
Web services like you're talking about tend to have a few layers between the actual data being received and the method that you've provided. For example:
Client sends message
Server receives message
Server translates message into something usable
Server provides usable message to web service method
In your case, you are wanting to emulate the same kind of functionality with a direct socket connection and no web service framework to do the heavy lifting for you, so you need to provide 2, 3, and 4 yourself.
It would help if you had a standard way of structuring your data so that you can provide information to the server, such as "Which method do you want to call?", and frankly, you can do it however you want. It's your client/server, you could use SOAP, JSON, you could even create your own fixed-length field format, as long as both sides speak in terms of the same data structure.
If you have specific implementation questions about a particular path you are going down, however, you are welcome to ask a different question.
Related
I am polling an OPCDA server for data every second. I use the standard .NET DLL's from OPC Foundation to achieve this.
My service is located on the same server as the OPCDA server. However, my read times are often around 900-1000ms. Is this normal or something wrong in my code or server setup? I poll around 20 OPCDA tags. What is a "standard" response time of such an operation or is it impossible to say?
It doesn't sound normal, but it's impossible to say for certain without knowing what the source of the data is.
Check documentation of OPC DA interface you use to fetch data from the server and what parameters you pass to it.
If you use synchronous reads then problem definitely on server side or its backend (meaning that it takes too much time for server to read actual data).
If you use asynchronous reads (subscriptions) check parameter named like 'update rate'. It defines how often new data will be sent to client. E.g. if it is 1 second client will receive new data NOT faster than 1 second.
Subscriptions are supported by all OPC DA versions. If server doesn't implement this interface you will not be able to read asynchronously and will get error code like 'not implemented'.
What OPC server are you using? There may be a setting to keep the update rate fixed or respect the client update rate.
I am working on a C# client for a server that wraps Netty. It is a TCP/IP server and I have tried using C# class TcpClient, but could not write anything onto the server or receive a printed response.
The Netty socket classes include the following: http://docs.jboss.org/netty/3.2/api/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.html http://docs.jboss.org/netty/3.2/api/org/jboss/netty/bootstrap/ClientBootstrap.html
The message is encoded as a byte[] in Java. Part of class PingSerializer, in the server code, reads as follows:
public byte[] requestToBytes(Ping message) {
return NorbertExampleProtos.Ping.newBuilder().setTimestamp(message.timestamp).build().toByteArray();
}
public Ping requestFromBytes(byte[] bytes) {
try {
return new Ping(NorbertExampleProtos.Ping.newBuilder().mergeFrom(bytes).build().getTimestamp());
} catch (InvalidProtocolBufferException e) {
System.out.println("Invalid protocol buffer exception " + e.getMessage());
throw new IllegalArgumentException(e);
}
}
I would like to know whether it is possible for a client written in C# to connect to the socket, ping the server and print out the server's response, without modifying the server code or using a cross-language development tool such as Apache Thrift or IKVM to handle the messages. Thanks, I would appreciate any help.
Judging by the code sample you've given, it looks like the data is encoded using Protocol Buffers, Google's serialization format.
Fortunately, there are at least two libraries implementing Protocol Buffers for .NET:
protobuf-net: Written for .NET from the ground up, this is a good choice if you don't particularly need the C# code to look like the equivalent Java/C++ code.
protobuf-csharp-port: This is a port from the Java client code, with some .NET idioms added - so if you're working with Protocol Buffers on multiple platforms, this may be more appropriate. (Disclaimer: I did most of the coding for this port.)
The good news is that the wire format for the two is the same, because it's the standard Protocol Buffer wire format. So if you decide later on that you've made the wrong choice, you don't need to worry about the data format changing.
In terms of communicating with the server, TcpClient should be absolutely fine. You'll need to find out exactly what the protocol is - for example, whether it's Protocol Buffers over HTTP, or something similar. (If it is over HTTP, WebClient would be a simpler approach.) However, beyond that it's straight TCP/IP: you write the bytes to the server, and it should write a reply. You can use Wireshark to look at the traffic between the client and the server, if you need to trace where problems are occurring.
There is an application called CS2J that will convert all of your C# code directly over to Java. However, you cannot expect it to be perfect and you will have a bit of debugging to do. It is supposed to very accurate.
Here I am troubleshooting a theoretical problem about HOW servers and clients are working on machines. I know all NET Processes, but I am missing something referring to code. I was unable to find something related about this.
I code in Visual C# 2008, i use regular TCPClient / TCPListener with 2 different projects:
Project1 (Client)
Project2 (Server)
My issues are maybe so simple:
1-> About how server receives data, event handlers are possible?
In my first server codes i used to make this loop:
while (true)
{
if (NetworkStream.DataAvailable)
{
//stuff
}
Thread.Sleep(200);
}
I encounter this as a crap way to control the incoming data from a server. BUT server is always ready to receive data.
My question: There is anything like...? ->
AcceptTcpClient();
I want a handler that waits until something happen, in this case a specific socket data receiving.
2-> General networking I/O methods.
The problem is (beside I'm a noob) is how to handle multiple data writing.
If I use to send a lot of data in a byte array, the sending can break if I send more data. All data got joined and errors occurs when receiving. I want to handle multiple writes to send and receive.
Is this possible?
About how server receives data, event handlers are possible?
If you want to write call-back oriented server code, you may find MSDN's Asynchronous Server Socket Example exactly what you're looking for.
... the sending can break if I send more data. All data got joined and errors occurs when receiving.
That is the nature of TCP. The standardized Internet protocols fall into a few categories:
block oriented stream oriented
reliable SCTP TCP
unreliable UDP ---
If you really want to send blocks of data, you can use SCTP, but be aware that many firewalls DROP SCTP packets because they aren't "usual". I don't know if you can reliably route SCTP packets across the open Internet.
You can wrap your own content into blocks of data with your own headers or add other "synchronization" mechanisms to your system. Consider an HTTP server: it must wait until it reads an entire request like:
GET /index.html HTTP/1.1␍␊
Host: www.example.com␍␊
␍␊
Until the server sees the CRLFCRLF sequence, it must keep the partially-read data in a buffer. The bytes might come in one at a time in a dozen or more packets. Or, if the client is sending multiple requests in a single stream, a dozen requests might come in a single packet.
You just have to handle this.
I have a C# application (which is the client) and I have a server. Now the server gets and sends all sorts of messages which are strings to the client, I am using StreamWriter for this, now the sending message on the client and the server looks pretty the same, I take the string encode it to UTF-8 and then send it
public void SendMessage(String p)
{
if (p != "")
{
string StringMessage = HttpUtility.UrlEncode(p, System.Text.Encoding.UTF8);
try
{
swSender.WriteLine(StringMessage);
swSender.Flush();
}
catch (IOException e)
{
//do some stuff
}
}
}
now,the strings I send is something like this:
"SUBJECT####SOMEDATA1<><>SOMEDATA2<><>SOMEDATA3
This causes some problems, and makes me think. Is this the way big applications send/ receive data? Because it looks pretty silly. If no, then can some one provide an example on how big applications send messages?
Also: my way of sending messages makes me make big nested if
For example:
if(Subject="something")
do something
else if(subject="something else")
do something else
How can I fix this?
It all greatly depends on your application's needs.
Generally speaking: no, inventing your own protocol is not a good idea.
There are quite a few ways to send messages from client to server.
I'd suggest you to do some reading on WCF, or if you are in .NET 2.0 than .NET Remoting.
Also, you might want to consider to send HTTP messages, as there are a shitload of frameworks to do that.
One way is to use XML-RPC. I used this for .NET. I followed the instructions w/o modifying it and got the client/server working within 30mins and another 10 to modify it to my liking. Essentially you call functions normally and through the magic of the library it will block for the server to execute the code and it will return results. RPC = remote procedure call.
If your using asp.net use the instructions labeled IIS even if your on linux using fastcgi or apache. I ignored that which was a mistake because it was labeled IIS. There is a .NET Remoting option (if the server isnt asp.net but another app) thats available.
A not as good option is to learn webclient and post json strings to the server. Then read the response as json. XML-RPC is pretty standard and suggested.
try to use HttpUtility.HtmlEncode Method
instead UrlEncode()
Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?
This is what I'm doing at the moment:
ChannelServices.RegisterChannel(new HttpChannel(), false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton);
MyServerObject = (IRemoteServer)Activator.GetObject(
typeof(IRemoteServer),
String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
The first two lines are in the server-side code, for marshaling out the server object, yes?
In that case, yes, the third line is the simplest you can get at client-side.
In addition, you can serve out additional server-side objects from the MyServerObject instance, if you include public accessors for them in IRemoteServer interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:
//obtain another marshalbyref object of the type ISessionManager:
ISessionManager = MyServerObject.GetSessionManager();
WCF.
I have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/correctly.
What’s the simplest way to connect to a .NET remote server object? WCF.