UDP Index out of range - sockets

I am trying to figure out why the client component of the array below is out of range. I know this happens when the element of an array that you are trying to access doesn't exist but I am new to Socket Programming and trying to write my first UDP script but not sure how to deal with it.
Client side code causing error at the args[0]:
class EmployeeUDPClient{
public static void Main(string[] args){
UdpClient udpc = new UdpClient(args[0],2055); //Line causing error
IPEndPoint ep = null;
while(true){
Console.Write("Name: ");
string name = Console.ReadLine();
if(name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
udpc.Send(sdata,sdata.Length);
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
Console.WriteLine(job);
}
}
}
This is the server side code which runs fine:
class EmployeeUDPServer{
public static void Main(){
UdpClient udpc = new UdpClient(2055);
Console.WriteLine("Server started, servicing on port 2055");
IPEndPoint ep = null;
while(true){
byte[] rdata = udpc.Receive(ref ep);
string name = Encoding.ASCII.GetString(rdata);
string job = ConfigurationSettings.AppSettings[name];
if(job == null) job = "No such employee";
byte[] sdata = Encoding.ASCII.GetBytes(job);
udpc.Send(sdata,sdata.Length,ep);
}
}
}
Any thoughts on why I get this error? I am running the 2 scripts on the same computer so could that be the reason?

The error is because you are not passing any arguments to the Main() function within your client class.
Change line:
UdpClient udpc = new UdpClient(2055);
To:
string[] host = new string[1];
host[0] = "127.0.0.1";
UdpClient udpc = new UdpClient(host);

Related

Why receiveData in UDP Socket contains "square" char?

When i run Server and Client, type a string form Client to Server, Server response that string and "square" char.
I have consulted many codes but the result is still the same........................................................................................................................................................................................................................................................................................................
My Server :
public class serverUDP {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
while(true) {
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[2048];
// receive packet
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String sentence_to_client = sentence+ " (server accpeted!)";
// send packet
sendData = sentence_to_client.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
My Client :
public class clientUDP {
public static void main(String args[]) throws Exception {
DatagramSocket clientSocket = new DatagramSocket(6789);
InetAddress IPAddress = InetAddress.getByName("localhost");
while(true){
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[2048];
// input
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
String sentence = inFromUser.readLine();
// send packet
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
// receive packet
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modified_Sentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modified_Sentence);
if(sentence.compareTo("quit") == 0)
break;
}
clientSocket.close();
}
}
Result: String + "square" char

Server Socket cannot accepts client. (C# UWP Async Socket Programming)

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.

Curator ServiceCacheListener is triggered three times when a service is added

I am learning zookeeper and trying out the Curator framework for service discoveries. However, I am facing a weird issue that I have difficulties to figure out. The problem is when I tried to register an instance via serviceDiscovery, the cacheChanged event of the serviceCache gets triggered three times. When I removed an instance, it is only triggered once, which is the expected behavior. Please see the code below:
public class DiscoveryExample {
private static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
// this is the ip address of my VM
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
.client(client)
.basePath(PATH)
.serializer(serializer)
.build();
serviceDiscovery.start();
ServiceCache<InstanceDetails> serviceCache = serviceDiscovery.serviceCacheBuilder()
.name("product")
.build();
serviceCache.addListener(new ServiceCacheListener() {
#Override
public void stateChanged(CuratorFramework curator, ConnectionState state) {
// TODO Auto-generated method stub
System.out.println("State Changed to " + state.name());
}
// THIS IS THE PART GETS TRIGGERED MULTIPLE TIMES
#Override
public void cacheChanged() {
System.out.println("Cached Changed ");
List<ServiceInstance<InstanceDetails>> list = serviceCache.getInstances();
Iterator<ServiceInstance<InstanceDetails>> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next().getAddress());
}
}
});
serviceCache.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
String line = in.readLine();
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
}
AND
public class RegisterApplicationServer {
final static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH)
.serializer(serializer).build();
serviceDiscovery.start();
// SOME OTHER CODE THAT TAKES CARES OF USER INPUT...
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
private static void addInstance(String[] args, CuratorFramework client, String command,
ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// simulate a new instance coming up
// in a real application, this would be a separate process
if (args.length < 2) {
System.err.println("syntax error (expected add <name> <description>): " + command);
return;
}
StringBuilder description = new StringBuilder();
for (int i = 1; i < args.length; ++i) {
if (i > 1) {
description.append(' ');
}
description.append(args[i]);
}
String serviceName = args[0];
ApplicationServer server = new ApplicationServer(client, PATH, serviceName, description.toString());
server.start();
serviceDiscovery.registerService(server.getThisInstance());
System.out.println(serviceName + " added");
}
private static void deleteInstance(String[] args, String command, ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// in a real application, this would occur due to normal operation, a
// crash, maintenance, etc.
if (args.length != 2) {
System.err.println("syntax error (expected delete <name>): " + command);
return;
}
final String serviceName = args[0];
Collection<ServiceInstance<InstanceDetails>> set = serviceDiscovery.queryForInstances(serviceName);
Iterator<ServiceInstance<InstanceDetails>> it = set.iterator();
while (it.hasNext()) {
ServiceInstance<InstanceDetails> si = it.next();
if (si.getPayload().getDescription().indexOf(args[1]) != -1) {
serviceDiscovery.unregisterService(si);
}
}
System.out.println("Removed an instance of: " + serviceName);
}
}
I appriciate if anyone can please point out where I am doing wrong and maybe can share some good materials/examples so I can refer to. The official website and the examples on github does not help a lot.

Asynchronous sockets in ring transfer

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...

SocketException was Unhandled by user code

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json.Linq;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPush_Click(object sender, EventArgs e)
{
pushMessage(txtDeviceID.Text.Trim(), txtPayload.Text.Trim());
}
public void pushMessage(string deviceID, string Mesaj)
{
int port = 2195;
String hostname = "ssl://gateway.sandbox.push.apple.com:2195";
String certificatePath = HttpContext.Current.Server.MapPath("PushNotifi.p12");
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "taxmann");
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Ssl3, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0); //The command
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
writer.Write(HexStringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":{\body\":\"" + Mesaj + "\"},\"badge\":1,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
lblResponse.Text = "Sucess..";
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
lblResponse.Text = ex.Message;
}
catch (Exception e)
{
client.Close();
lblResponse.Text = e.Message;
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
else // Do not allow this client to communicate with unauthenticated servers.
return false;
}
private static byte[] HexStringToByteArray(String DeviceID)
{
//convert Devide token to HEX value.
byte[] deviceToken = new byte[DeviceID.Length / 2];
for (int i = 0; i < deviceToken.Length; i++)
deviceToken[i] = byte.Parse(DeviceID.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
return deviceToken;
}
}
}
This is my code. When I run this, then
SocketException was unhandled by user code
on line
TcpClient client = new TcpClient(host-name, port);
when googling system.net.sockets.socketexception and not recognize ssl://gateway.sandbox.push.apple.com:2195 host name
How can I fix this?
Basically this code is for sending Push Notifications to an iPhone application.
I'm using localhost as the server for sending the notification.
I think the problem is your hostname string:
int port = 2195;
String hostname = "ssl://gateway.sandbox.push.apple.com:2195";
TcpClient client = new TcpClient(hostname, port);
The port value (2195) is a separate constructor parameter, so I don't think you should be passing it in the hostname parameter, as well.
Also, the protocol (e.g. ssl://) shouldn't be part of the hostname. The SslStream tells .NET that this is SSL.
If you look at this similar question on stack overflow, you'll see that they use something like this:
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
TcpClient client = new TcpClient(hostname, port);
P.S. I think you also had it right, in your original question on this subject