WCF Socket Connection Aborted: Communication Exception - c#

I'm having some difficulty setting up a WCF interface. I can connect fine, but as soon as I start sending certain data, I get the following exception:
The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '01:39:59.9084817'.
From looking at a few other questions, I found that this could be due to inefficient timeout. So I increased the following parameters to 100 minutes just for kicks.
tcpBinding.ReceiveTimeout = TimeSpan.FromMinutes(100);
tcpBinding.OpenTimeout = TimeSpan.FromMinutes(100);
tcpBinding.SendTimeout = TimeSpan.FromMinutes(100);
However, this exception is thrown the same instant a certain function is called so I don't think that is the problem. The peculiar thing though is that the exception always shows a time almost the same as whatever I put into those parameters, regardless of how much time actually passed.
I found that I can send the standard types like object, string, int, etc but whenever I try to send a custom type, this error is thrown. That is telling me it might be a bad reference somewhere. Does this make sense?
UPDATE:
Had a chance to upload the code.
Here is the client side:
namespace GenericWCF
{
/// <summary>
/// TODO: Update summary.
/// </summary>
[ServiceContract()]
public interface SimWCFInterface
{
[OperationContract()]
void SimpleMessage(string message);
[OperationContract()]
List<CustomObj> GetDataPoints();
}
}
and the server side:
namespace DifferentNamespace
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// TODO: Update summary.
/// </summary>
[ServiceContract()]
public interface SimWCFInterface
{
[OperationContract()]
void SimpleMessage(string message);
[OperationContract()]
List<CustomObj> GetDataPoints();
}
and the actual implementation
namespace DifferentNamespace
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// TODO: Update summary.
/// </summary>
[ServiceContract()]
public interface SimWCFInterface
{
public void SimpleMessage(string message)
{
Debug.WriteLine("This is a simple message wcf");
MessageBox.Show(message);
}
public List<CustomObj> GetDataPoints()
{
List<CustomObj> points = new List<CustomObj>();
return points;
}
}
So there really isn't anything special going on I don't think. SimpleMessage runs fine no problem. If I change GetDataPoints to return a regular object, it works fine as well. The problem only occurs when I return that CustomObj. One thing I noticed just now is that client and server side live in different namespaces, so could that be an issue? Also, I'm using a tcp conneciton. I'll post that code in a moment.
EDIT:
The tcp connection code:
client
private string endPointAddress;
private NetTcpBinding tcpBinding;
public void Connect(string ipAddress, string portNumber, string interfaceName)
{
try
{
interfaceName = interfaceName.Substring(interfaceName.LastIndexOf(".") + 1);
endPointAddress = "net.tcp://" + ipAddress + ":" + portNumber + "/" + interfaceName;
tcpBinding = new NetTcpBinding();
tcpBinding.TransactionFlow = false;
tcpBinding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
tcpBinding.Security.Mode = SecurityMode.None;
tcpBinding.ReceiveTimeout = TimeSpan.FromMinutes(100);
tcpBinding.OpenTimeout = TimeSpan.FromMinutes(100);
tcpBinding.SendTimeout = TimeSpan.FromMinutes(100);
tcpBinding.ReliableSession.Ordered = false;
tcpBinding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;
tcpBinding.MaxReceivedMessageSize = 10000000;
tcpBinding.MaxBufferPoolSize = 10000000;
tcpBinding.MaxBufferSize = 10000000;
EndpointAddress endpointAddress = new EndpointAddress(endPointAddress);
_SimChannelFactory = new ChannelFactory<SimWCFInterface>(tcpBinding, endpointAddress);
_SimWCFInterface = _SimChannelFactory.CreateChannel();
//test connection...working
_SimWCFInterface.SimpleMessage("what a message");
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
and the server
static public void CreateSimHost(string IPAdd, string port, Type interfaceType, Type serviceType)
{
try
{
string interfaceName = interfaceType.ToString();
interfaceName = interfaceName.Substring(interfaceName.LastIndexOf(".") + 1);
// Create the url that is needed to specify where the service should be started
urlService = "net.tcp://" + IPAdd + ":" + port + "/" + interfaceName;
host = new ServiceHost(serviceType);
// The binding is where we can choose what transport layer we want to use. HTTP, TCP ect.
tcpBinding = new NetTcpBinding
{
TransactionFlow = false
};
tcpBinding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
tcpBinding.Security.Mode = SecurityMode.None; // <- Very crucial
tcpBinding.ReceiveTimeout = TimeSpan.MaxValue;
tcpBinding.SendTimeout = TimeSpan.MaxValue;
tcpBinding.ReliableSession.Ordered = false;
tcpBinding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;
// Add a endpoint
host.AddServiceEndpoint(interfaceType, tcpBinding, urlService);
host.Open();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}

Related

Reuse MQMessage object

I have this test code that listens for messages forever. If it gets one it prints it out. What I want to do is avoid having to construct a MQMessage object prior to each get(). How do i reuse a MQMessage for multiple calls to get()?
using System;
using IBM.WMQ;
namespace WMQ {
class Program {
static void Main(string[] args) {
string QueueManagerName = "A1PATA00";
string channelName = "ECACHE";
string connectionName = "A1PATA00.WORLDSPAN.COM(1414)";
var queueManager = new MQQueueManager(QueueManagerName, channelName, connectionName);
MQQueue get = queueManager.AccessQueue("SPLASH.ECAC.2", MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQGMO_FAIL_IF_QUIESCING);
var gmo = new MQGetMessageOptions();
gmo.Options = MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_WAIT;
gmo.WaitInterval = 10000000;// wait time
// var queueMessage = new MQMessage(); <--- i want to do this new once!
while (true) {
var queueMessage = new MQMessage(); // <-- only works if I do this every time i do a get
get.Get(queueMessage, gmo);
var strReturn = queueMessage.ReadString(queueMessage.MessageLength);
Console.WriteLine(strReturn);
}
}
}
}
When I see questions like this, I shake my head. You do not
understand object oriented concepts in the .NET VM (framework) and
garbage collection.
Also, why don't you write pure C# code?
Finally, in a world where security is very important, your code does
not support either SSL/TLS and/or UserID & Password authentication.
(1) Please notice where I am defining the MQMessage object (very important).
There is basically no difference in memory usage or speed between the following 2 code snippets:
(A)
MQMessage msg = null;
while (true)
{
msg = new MQMessage();
get.Get(msg, gmo);
Console.WriteLine(msg.ReadString(msg.MessageLength));
}
(B)
MQMessage msg = new MQMessage();
while (true)
{
get.Get(msg, gmo);
Console.WriteLine(msg.ReadString(msg.MessageLength));
msg.ClearMessage();
msg.MessageId = MQC.MQMI_NONE;
msg.CorrelationId = MQC.MQCI_NONE;
}
I prefer (A) because it is cleaner and easier to read.
(2) When you use 'var', you are forcing the .NET framework to guess at what you are doing. Do pure object oriented programming.
i.e.
MQMessage msg = new MQMessage();
(3) Explicitly setting the channel name and connection name in the MQQueueManager does not allow setting of MQ security information. Also, do NOT use the MQEnvironment class as it is NOT thread safe. It is far better to put all the information in a Hashtable and pass the Hashtable to the MQQueueManager class. Here is a MQ .NET managed-mode example using a Hashtable for MQ connection information:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;
namespace MQTest02
{
class MQTest02
{
private Hashtable inParms = null;
private Hashtable qMgrProp = null;
private System.String qManager;
private System.String outputQName;
/*
* The constructor
*/
public MQTest02()
: base()
{
}
/// <summary> Make sure the required parameters are present.</summary>
/// <returns> true/false
/// </returns>
private bool allParamsPresent()
{
bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
inParms.ContainsKey("-q");
if (b)
{
try
{
System.Int32.Parse((System.String)inParms["-p"]);
}
catch (System.FormatException e)
{
b = false;
}
}
return b;
}
/// <summary> Extract the command-line parameters and initialize the MQ variables.</summary>
/// <param name="args">
/// </param>
/// <throws> IllegalArgumentException </throws>
private void init(System.String[] args)
{
inParms = Hashtable.Synchronized(new Hashtable());
if (args.Length > 0 && (args.Length % 2) == 0)
{
for (int i = 0; i < args.Length; i += 2)
{
inParms[args[i]] = args[i + 1];
}
}
else
{
throw new System.ArgumentException();
}
if (allParamsPresent())
{
qManager = ((System.String)inParms["-m"]);
outputQName = ((System.String)inParms["-q"]);
qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));
try
{
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (inParms.ContainsKey("-u"))
qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));
if (inParms.ContainsKey("-x"))
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));
if (inParms.ContainsKey("-s"))
qMgrProp.Add(MQC.SECURITY_EXIT_PROPERTY, ((System.String)inParms["-s"]));
System.Console.Out.WriteLine("MQTest02:");
Console.WriteLine(" QMgrName ='{0}'", qManager);
Console.WriteLine(" Output QName ='{0}'", outputQName);
System.Console.Out.WriteLine("QMgr Property values:");
foreach (DictionaryEntry de in qMgrProp)
{
Console.WriteLine(" {0} = '{1}'", de.Key, de.Value);
}
}
else
{
throw new System.ArgumentException();
}
}
/// <summary> Connect, open queue, read a message, close queue and disconnect.
///
/// </summary>
/// <throws> MQException </throws>
private void testReceive()
{
MQQueueManager qMgr = null;
MQQueue queue = null;
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING;
MQGetMessageOptions gmo = new MQGetMessageOptions();
MQMessage receiveMsg = null;
try
{
qMgr = new MQQueueManager(qManager, qMgrProp);
System.Console.Out.WriteLine("MQTest02 successfully connected to " + qManager);
queue = qMgr.AccessQueue(outputQName, openOptions, null, null, null); // no alternate user id
System.Console.Out.WriteLine("MQTest02 successfully opened " + outputQName);
receiveMsg = new MQMessage();
queue.Get(receiveMsg, gmo);
System.Console.Out.WriteLine("Message Data>>>" + receiveMsg.ReadString(receiveMsg.MessageLength));
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest02 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("MQTest02 ioex=" + ioex);
}
finally
{
try
{
queue.Close();
System.Console.Out.WriteLine("MQTest02 closed: " + outputQName);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest02 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
try
{
qMgr.Disconnect();
System.Console.Out.WriteLine("MQTest02 disconnected from " + qManager);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest02 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
}
}
/// <summary> main line</summary>
/// <param name="args">
/// </param>
// [STAThread]
public static void Main(System.String[] args)
{
MQTest02 mqt = new MQTest02();
try
{
mqt.init(args);
mqt.testReceive();
}
catch (System.ArgumentException e)
{
System.Console.Out.WriteLine("Usage: MQTest02 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd] [-s securityExit]");
System.Environment.Exit(1);
}
catch (MQException e)
{
System.Console.Out.WriteLine(e);
System.Environment.Exit(1);
}
System.Environment.Exit(0);
}
}
}
To run MQTest02 using your information, it would be:
MQTest02.exe -h A1PATA00.WORLDSPAN.COM -p 1414 -m A1PATA00 -c ECACHE -q SPLASH.ECAC.2
In the IBM MQ Knowledge center page "ClearMessage method" it documents the following:
This method clears the data buffer portion of the MQMessage object.
Any Message Data in the data buffer is lost, because MessageLength,
DataLength, and DataOffset are all set to zero.
The Message Descriptor (MQMD) portion is unaffected; an application
might need to modify some of the MQMD fields before reusing the
MQMessage object. To set the MQMD fields back use New to replace the
object with a new instance.
In the IBM MQ Knowledge center page "MQMessage .NET class" it documents the following:
public byte[] MessageId {get; set;}
For an MQQueue.Get call, this field specifies the message identifier
of the message to be retrieved. Normally, the queue manager returns
the first message with a message identifier and correlation identifier
that match the message descriptor fields. Allow any message identifier
to match using the special value MQC.MQMI_NONE.
public byte[] CorrelationId {get; set;}
For an MQQueue.Get call, the correlation identifier of the message to
be retrieved. The queue manager returns the first message with a
message identifier and a correlation identifier that match the message
descriptor fields. The default value, MQC.MQCI_NONE, helps any
correlation identifier to match.
Try this:
var queueMessage = new MQMessage(); <--- i want to do this new once!
while (true) {
//var queueMessage = new MQMessage(); // <-- only works if I do this every time i do a get
queueMessage.ClearMessage();
queueMessage.MessageId = MQC.MQMI_NONE;
queueMessage.CorrelationId = MQC.MQCI_NONE;
get.Get(queueMessage, gmo);

Connecting to the MQ Server using CCDT

I'm trying to connect to the MQ using the information present in the CCDT file. I can currently connect to the MQ using all the details, and get and put messages from and to the queue.
After extensive googling, I've been unable to find any sample code which allows me to connect using the CCDT file.
One of my colleagues forwarded me his JMS connection code, but I've been unable to port it to C#.
The JAVA code is as follows -
public class MQTest {
public static void main(String[] args) {
MQQueueManager queueManager = null;
URL ccdtFileUrl = null;
MQMessage mqMessage = null;
//MQPutMessageOptions myPMO = null
try {
String QM = "IB9QMGR";
String QUEUE1 = "TEST";
System.out.println("Starting MQClient Put Program: ");
ccdtFileUrl = new URL("file:///D:/AMQCLCHL.TAB") ;
ccdtFileUrl.openConnection();
queueManager = new MQQueueManager("SDCQMGR.T1", ccdtFileUrl);
System.out.println("Connected to QMGR ");
int openOptions = MQC.MQOO_OUTPUT;
MQQueue InQueue = queueManager.accessQueue(QUEUE1,openOptions,null,null,null);
MQMessage inMessage = new MQMessage();
inMessage.writeString("###Testing####");
InQueue.put(inMessage);
System.out.println("Message Id is :" + inMessage.messageId);
System.out.println(inMessage.toString());
InQueue.close();
queueManager.disconnect() ;
}
catch(MQException ex){
System.out.println("MQ Error - Reason code :" + ex.reasonCode);
}
catch (Exception e){
System.out.println("Error : " + e);
}
}
}
Instead of URL, I used the URI (in C#) to set file location. (This may be wrongly used. Not sure what else to use though.)
Uri ccdtFileUrl = new Uri("file:///D:/AMQCLCHL.TAB") ;
but I can't use openConnection() on a URI. Also,
queueManager = new MQQueueManager("SDCQMGR.T1",ccdtFileUrl);
gives an argument overload exception. As URI is not supported in C#.
I've tried looking up samples but I've found some JMS samples and thats it. Looking for some sample code to connect in C#.
You will need to set MQCHLLIB and MQCHLTAB environment variables to use CCDT. You can set these two variables either from command prompt,app.config or code in the application itself.
Following example demonstrates usage of CCDT:
MQQueueManager qm = null;
System.Environment.SetEnvironmentVariable("MQCHLLIB", "C:\\ProgramData\\IBM\\MQ\\qmgrs\\QM1\\#ipcc");
System.Environment.SetEnvironmentVariable("MQCHLTAB", "AMQCLCHL.TAB");
try
{
**Hashtable props = new Hashtable();
props.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
qm = new MQQueueManager("QM1",props);**
MQQueue queue1 = qm.AccessQueue("SYSTEM.DEFAULT.LOCAL.QUEUE", MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING);
MQMessage msg = new MQMessage();
msg.WriteUTF("Hello this message is from .net client");
queue1.Put(msg);
queue1.Close();
qm.Disconnect();
}
catch (Exception ex)
{
Console.Write(ex);
}

C# as Websocket server for HTML5 websocket connection

I guess it's already time that I ask others. Is it possible to create a websocket server using C# and server request from HTML5 codes?
I am currently using the System package for websocket. I have a code that I downloaded over the internet and here it is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebSocketChatServer
{
using WebSocketServer;
class ChatServer
{
WebSocketServer wss;
List<User> Users = new List<User>();
string unknownName = "john doe";
public ChatServer()
{
// wss = new WebSocketServer(8181, "http://localhost:8080", "ws://localhost:8181/chat");
wss = new WebSocketServer(8080, "http://localhost:8080", "ws://localhost:8080/dotnet/Chats");
wss.Logger = Console.Out;
wss.LogLevel = ServerLogLevel.Subtle;
wss.ClientConnected += new ClientConnectedEventHandler(OnClientConnected);
wss.Start();
KeepAlive();
}
private void KeepAlive()
{
string r = Console.ReadLine();
while (r != "quit")
{
if(r == "users")
{
Console.WriteLine(Users.Count);
}
r = Console.ReadLine();
}
}
void OnClientConnected(WebSocketConnection sender, EventArgs e)
{
Console.WriteLine("test");
Users.Add(new User() { Connection = sender });
sender.Disconnected += new WebSocketDisconnectedEventHandler(OnClientDisconnected);
sender.DataReceived += new DataReceivedEventHandler(OnClientMessage);
}
void OnClientMessage(WebSocketConnection sender, DataReceivedEventArgs e)
{
Console.WriteLine(sender);
User user = Users.Single(a => a.Connection == sender);
if (e.Data.Contains("/nick"))
{
string[] tmpArray = e.Data.Split(new char[] { ' ' });
if (tmpArray.Length > 1)
{
string myNewName = tmpArray[1];
while (Users.Where(a => a.Name == myNewName).Count() != 0)
{
myNewName += "_";
}
if (user.Name != null)
wss.SendToAll("server: '" + user.Name + "' changed name to '" + myNewName + "'");
else
sender.Send("you are now know as '" + myNewName + "'");
user.Name = myNewName;
}
}
else
{
string name = (user.Name == null) ? unknownName : user.Name;
wss.SendToAllExceptOne(name + ": " + e.Data, sender);
sender.Send("me: " + e.Data);
}
}
void OnClientDisconnected(WebSocketConnection sender, EventArgs e)
{
try
{
User user = Users.Single(a => a.Connection == sender);
string name = (user.Name == null) ? unknownName : user.Name;
wss.SendToAll("server: "+name + " disconnected");
Users.Remove(user);
}
catch (Exception exc)
{
Console.WriteLine("ehm...");
}
}
}
}
And I have this code for client side:
<!HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function(){
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(){
alert("Socket has been opened!");
}
});
</script>
</head>
</HTML>
As I run my C# console app and load the client page, the app tells me that there's someone who connected in the port it is listening to. But on my client side, as I look in firebug's console, it gives me the beginner's classic error:
Firefox can't establish a connection to the server at ws://localhost:8080/
What I would like to achieve is establish first a successful websocket connection and push value to my client coming from my server.
I have considered Alchemy but the version I have is Visual Studio express 2010, the free version, and it says that "solution folders are not supported in this version of application".
Any help will be very much appreciated.
I've been developing a server for a JavaScript/HTML 5 game for about 7 months now have you looked into Alchemy Websockets? its pretty easy to use.
Example:
using Alchemy;
using Alchemy.Classes;
namespace GameServer
{
static class Program
{
public static readonly ConcurrentDictionary<ClientPeer, bool> OnlineUsers = new ConcurrentDictionary<ClientPeer, bool>();
static void Main(string[] args)
{
var aServer = new WebSocketServer(4530, IPAddress.Any)
{
OnReceive = context => OnReceive(context),
OnConnected = context => OnConnect(context),
OnDisconnect = context => OnDisconnect(context),
TimeOut = new TimeSpan(0, 10, 0),
FlashAccessPolicyEnabled = true
};
}
private static void OnConnect(UserContext context)
{
var client = new ClientPeer(context);
OnlineUsers.TryAdd(client, false);
//Do something with the new client
}
}
}
As you can see its pretty easy to work with and I find their documentation very good (note ClientPeer is a custom class of mine just using it as an example).
What you are trying to achieve will be far easier if you take a look at ASP.NET SignalR
It has support for high level hubs to implement realtime communication and also has a persistent connection low level class to have a finely grained control over the communication.
Support for multiple client types and fallback if websockets isn't supported at both ends of the communication (it can optionally use long polling or forever frames).
The reason for this error is ( probably ) because you are not responding to the handshake. Once the connection is established browser sends some data and the server must respond appropriately ( otherwise browser will close the connection ). You can read more about this on wiki or directly in specification.
I modified a code i downloaded online and here's what I got now:
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
namespace WebSocketServer
{
public enum ServerLogLevel { Nothing, Subtle, Verbose };
public delegate void ClientConnectedEventHandler(WebSocketConnection sender, EventArgs e);
public class WebSocketServer
{
#region private members
private string webSocketOrigin; // location for the protocol handshake
private string webSocketLocation; // location for the protocol handshake
#endregion
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static IPEndPoint ipLocal;
public event ClientConnectedEventHandler ClientConnected;
/// <summary>
/// TextWriter used for logging
/// </summary>
public TextWriter Logger { get; set; } // stream used for logging
/// <summary>
/// How much information do you want, the server to post to the stream
/// </summary>
public ServerLogLevel LogLevel = ServerLogLevel.Subtle;
/// <summary>
/// Gets the connections of the server
/// </summary>
public List<WebSocketConnection> Connections { get; private set; }
/// <summary>
/// Gets the listener socket. This socket is used to listen for new client connections
/// </summary>
public Socket ListenerSocker { get; private set; }
/// <summary>
/// Get the port of the server
/// </summary>
public int Port { get; private set; }
public WebSocketServer(int port, string origin, string location)
{
Port = port;
Connections = new List<WebSocketConnection>();
webSocketOrigin = origin;
webSocketLocation = location;
}
/// <summary>
/// Starts the server - making it listen for connections
/// </summary>
public void Start()
{
// create the main server socket, bind it to the local ip address and start listening for clients
ListenerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
ipLocal = new IPEndPoint(IPAddress.Loopback, Port);
ListenerSocker.Bind(ipLocal);
ListenerSocker.Listen(100);
LogLine(DateTime.Now + "> server stated on " + ListenerSocker.LocalEndPoint, ServerLogLevel.Subtle);
ListenForClients();
}
// look for connecting clients
private void ListenForClients()
{
ListenerSocker.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
private void OnClientConnect(IAsyncResult asyn)
{
byte[] buffer = new byte[1024];
string headerResponse = "";
// create a new socket for the connection
var clientSocket = ListenerSocker.EndAccept(asyn);
var i = clientSocket.Receive(buffer);
headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
//Console.WriteLine(headerResponse);
if (clientSocket != null)
{
// Console.WriteLine("HEADER RESPONSE:"+headerResponse);
var key = headerResponse.Replace("ey:", "`")
.Split('`')[1] // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
.Replace("\r", "").Split('\n')[0] // dGhlIHNhbXBsZSBub25jZQ==
.Trim();
var test1 = AcceptKey(ref key);
var newLine = "\r\n";
var name = "Charmaine";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
+ "Testing lang naman po:" + name
;
// which one should I use? none of them fires the onopen method
clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
}
// keep track of the new guy
var clientConnection = new WebSocketConnection(clientSocket);
Connections.Add(clientConnection);
// clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected);
Console.WriteLine("New user: " + ipLocal);
// invoke the connection event
if (ClientConnected != null)
ClientConnected(clientConnection, EventArgs.Empty);
if (LogLevel != ServerLogLevel.Nothing)
clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);
// listen for more clients
ListenForClients();
}
void ClientDisconnected(WebSocketConnection sender, EventArgs e)
{
Connections.Remove(sender);
LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + " disconnected", ServerLogLevel.Subtle);
}
void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e)
{
Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint, ServerLogLevel.Subtle);
Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose);
LogLine("", ServerLogLevel.Subtle);
}
/// <summary>
/// send a string to all the clients (you spammer!)
/// </summary>
/// <param name="data">the string to send</param>
public void SendToAll(string data)
{
Connections.ForEach(a => a.Send(data));
}
/// <summary>
/// send a string to all the clients except one
/// </summary>
/// <param name="data">the string to send</param>
/// <param name="indifferent">the client that doesn't care</param>
public void SendToAllExceptOne(string data, WebSocketConnection indifferent)
{
foreach (var client in Connections)
{
if (client != indifferent)
client.Send(data);
}
}
/// <summary>
/// Takes care of the initial handshaking between the the client and the server
/// </summary>
private void Log(string str, ServerLogLevel level)
{
if (Logger != null && (int)LogLevel >= (int)level)
{
Logger.Write(str);
}
}
private void LogLine(string str, ServerLogLevel level)
{
Log(str + "\r\n", level);
}
private static string AcceptKey(ref string key)
{
string longKey = key + guid;
byte[] hashBytes = ComputeHash(longKey);
return Convert.ToBase64String(hashBytes);
}
static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
private static byte[] ComputeHash(string str)
{
return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
}
private void ShakeHands(Socket conn)
{
using (var stream = new NetworkStream(conn))
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
//read handshake from client (no need to actually read it, we know its there):
LogLine("Reading client handshake:", ServerLogLevel.Verbose);
string r = null;
while (r != "")
{
r = reader.ReadLine();
LogLine(r, ServerLogLevel.Verbose);
}
// send handshake to the client
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: " + webSocketOrigin);
writer.WriteLine("WebSocket-Location: " + webSocketLocation);
writer.WriteLine("");
}
// tell the nerds whats going on
LogLine("Sending handshake:", ServerLogLevel.Verbose);
LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
LogLine("", ServerLogLevel.Verbose);
LogLine("Started listening to client", ServerLogLevel.Verbose);
//conn.Listen();
}
}
}
Connection issue resolved, next would be SENDING DATA to client.
just change shakehands in WebSocketServer.cs file in solution with below code and your error will gone..
private void ShakeHands(Socket conn)
{
using (var stream = new NetworkStream(conn))
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
//read handshake from client (no need to actually read it, we know its there):
LogLine("Reading client handshake:", ServerLogLevel.Verbose);
string r = null;
Dictionary<string, string> headers = new Dictionary<string, string>();
while (r != "")
{
r = reader.ReadLine();
string[] tokens = r.Split(new char[] { ':' }, 2);
if (!string.IsNullOrWhiteSpace(r) && tokens.Length > 1)
{
headers[tokens[0]] = tokens[1].Trim();
}
LogLine(r, ServerLogLevel.Verbose);
}
//string line = string.Empty;
//while ((line = reader.ReadLine()) != string.Empty)
//{
// string[] tokens = line.Split(new char[] { ':' }, 2);
// if (!string.IsNullOrWhiteSpace(line) && tokens.Length > 1)
// {
// headers[tokens[0]] = tokens[1].Trim();
// }
//}
string responseKey = "";
string key = string.Concat(headers["Sec-WebSocket-Key"], "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
using (SHA1 sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
responseKey = Convert.ToBase64String(hash);
}
// send handshake to the client
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: " + webSocketOrigin);
writer.WriteLine("WebSocket-Location: " + webSocketLocation);
//writer.WriteLine("Sec-WebSocket-Protocol: chat");
writer.WriteLine("Sec-WebSocket-Accept: " + responseKey);
writer.WriteLine("");
}
// tell the nerds whats going on
LogLine("Sending handshake:", ServerLogLevel.Verbose);
LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
LogLine("", ServerLogLevel.Verbose);
LogLine("Started listening to client", ServerLogLevel.Verbose);
//conn.Listen();
}
You may also take a look at the WebSocketRPC library which should be pretty simple to use, for both the "raw" connection and the RPC connections (the messages can also be mixed).
The following can be useful to you:
The code responsible for sending/receiving raw messages is located in the Connection class.
In the repository you can also find how a base JavaScript client is implemented.
Disclaimer: I am the author.

Can't connect to NetTcpBinding WCF service due to "There was no endpoint listening" error

Could you guys please point what I'm missing here ?
I have two sample projects. Both console applications (.Net 3.5). Here is "server" side:
class Program
{
static void Main()
{
var baseAddresses = new Uri("net.tcp://localhost:9000/WcfServiceLibrary/svc");
var host = new ServiceHost(typeof(UiWcfSession), baseAddresses);
var reliableSession = new ReliableSessionBindingElement { Ordered = true, InactivityTimeout = TimeSpan.MaxValue };
var binding = new CustomBinding(reliableSession, new TcpTransportBindingElement()) { ReceiveTimeout = TimeSpan.MaxValue };
host.AddServiceEndpoint(typeof(IClientFulfillmentPipeService), binding, k.WinSvcEndpointName);
host.Open();
Thread.CurrentThread.Join();
}
}
Not sure if it's important but here is small snippet of IClientFulfillmentPipeService
[ServiceContract(CallbackContract = typeof (IClientFulfillmentPipeServiceCallbacks), SessionMode = SessionMode.Required)]
public interface IClientFulfillmentPipeService
{
[OperationContract(IsOneWay = true)]
void Initialize(int uiProcessId, string key);
}
[ServiceContract]
public interface IClientFulfillmentPipeServiceCallbacks
{
[OperationContract(IsOneWay = true)]
void ShowBalloonTip(int timeout, string tipTitle, string tipText, BalloonTipIcon tipIcon);
}
and finally client
private void OpenConnection()
{
try
{
var ep = new EndpointAddress("net.tcp://localhost:9000/WcfServiceLibrary/svc");
var reliableSession = new ReliableSessionBindingElement {Ordered = true};
Binding binding = new CustomBinding(reliableSession, new TcpTransportBindingElement());
reliableSession.InactivityTimeout = TimeSpan.MaxValue;
var pipeFactory = new DuplexChannelFactory<IClientFulfillmentPipeService>(this, binding, ep);
commChannel = pipeFactory.CreateChannel();
((IChannel) commChannel).Open(OpenConnectionTimeout);
}
catch (Exception ex)
{
Log.ErrorFormat("The communication channel to the windows service could not be established. {0}", ex.Message);
}
}
The client fails with System.ServiceModel.EndpointNotFoundException exception which says: "There was no endpoint listening at net.tcp://localhost:9000/WcfServiceLibrary/svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
This is modification of production code which is using named pipes and I want to convert it to Tcp transport.
Thanks!
I accidentally left k.WinSvcEndpointName in the endpoint definition in the server. That was the problem.

WCF With NetTCP across machines on the same network

I'm trying to implement some cross process communication that is between multiple computers and one server on the same network. What I'm trying right now is to use WCF with NetTcpBinding, hosted within my application which works on the same machine, but when I try to connect from another machine it throws a SSPI security error.
I've found lots of examples of doing this cross-machine, but all involve an app.config file which I would REALLY like to avoid. I want to be able to embed this functionality in a DLL that has not other dependencies (i.e. config files) for which I can just pass into it all of the necessary server addresses, etc and it will work. Is there anyway to setup this security (via the endpoints, etc) purely in code?
I'm testing this all out with the code below:
SERVER:
using System;
using System.ServiceModel;
namespace WCFServer
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
public class StringReverser : IStringReverser
{
public string ReverseString(string value)
{
char[] retVal = value.ToCharArray();
int idx = 0;
for (int i = value.Length - 1; i >= 0; i--)
retVal[idx++] = value[i];
string result = new string(retVal);
Console.WriteLine(value + " -> " + result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
var uri = "net.tcp://" + System.Net.Dns.GetHostName() + ":9985";
Console.WriteLine("Opening connection on: " + uri);
using (ServiceHost host = new ServiceHost(
typeof(StringReverser),
new Uri[]{
new Uri("net.tcp://" + System.Net.Dns.GetHostName() + ":9985")
}))
{
host.AddServiceEndpoint(typeof(IStringReverser),
new NetTcpBinding(),
"TcpReverse");
host.Open();
Console.WriteLine("Service is available. " +
"Press <ENTER> to exit.");
Console.ReadLine();
host.Close();
}
}
}
}
CLIENT:
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace WCFClient
{
[ServiceContract]
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
class Program
{
static void Main(string[] args)
{
var ep = "net.tcp://SERVER:9985/TcpReverse";
ChannelFactory<IStringReverser> pipeFactory =
new ChannelFactory<IStringReverser>(
new NetTcpBinding(),
new EndpointAddress(
ep));
IStringReverser pipeProxy =
pipeFactory.CreateChannel();
Console.WriteLine("Connected to: " + ep);
while (true)
{
string str = Console.ReadLine();
Console.WriteLine("pipe: " +
pipeProxy.ReverseString(str));
}
}
}
}
Security is normally configured on the binding. You are using NetTcpBinding with its defaults which means that Transport security is enabled.
On both, server and client, you should assign the NetTcpBinding instance to a local variable so that you can change the security (and possibly other) settings, and then use that variable when calling AddServiceEndpoint or when creating the ChannelFactory.
Sample:
var binding = new NetTcpBinding();
// disable security:
binding.Security.Mode = SecurityMode.None;
This is probably an issue with the SPN that your service is running under. It's most likely a machine account instead of a domain account. There's more information in this thread.
UPDATE: There's information in there about setting the SPN programmatically, but it's buried a few clicks in... here's a direct link (see the last section of the page).

Categories

Resources