I am battling to connect to a website using udpclient. Whenever I connect to localhost, I have no problems. This is the code I am using :'
private void button1_Click(object sender, EventArgs e)
{
UdpClient udpClient = new UdpClient();
udpClient.Connect("www.ituran.com/ituranmobileservice/mobileservice.asmx", 45004);
Byte[] btSendData = Encoding.ASCII.GetBytes("TESTING");
udpClient.Send(btSendData, btSendData.Length);
}
public void serverThread()
{
try
{
UdpClient udpClient = new UdpClient(45004);
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] btRecieve = udpClient.Receive(ref RemoteIpEndPoint);
string strReturnData = Encoding.ASCII.GetString(btRecieve);
Console.WriteLine(RemoteIpEndPoint.Address.ToString() + ":" + strReturnData.ToString());
}
}
catch (Exception ex)
{
using (StreamWriter sw = new StreamWriter("TEST_errorLog.txt", true))
{
sw.WriteLine();
sw.WriteLine(ex.ToString());
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
thdUDPServer.IsBackground = true;
thdUDPServer.Start();
}
The people that sent me the URL has confimed five times that the address and port is correct. How can I connect to that address?
Any help would be appreciated.
Change the host name to just www.ituran.com. There are no paths in UDP - you are just sending packets to a port on a server.
Related
I am creating a C# application in which I send files over a LAN connection via sockets, but I encounter an "System.NotSupportedException" when I call the Send function
This is the function of the receiver of the file.
Socket _newSocket;
List<byte> endBuffer;
// Used to connect to the server
private void button1_Click(object sender, EventArgs e)
{
_newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_newSocket.Connect(IPAddress.Parse("127.0.0.1"), _PORT);
}
// Used to Receive the file
private void button3_Click(object sender, EventArgs e)
{
_newSocket.Receive(endBuffer.ToArray(), SocketFlags.None);
MessageBox
.Show(Encoding.ASCII.GetString(endBuffer.ToArray(), 0, endBuffer.Count));
}
This is the function I used to start the server.
void SetupServer(object sender)
{
Button temp = (Button)sender;
temp.Enabled = false;
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(new IPEndPoint(IPAddress.Parse(txtConnectToIP.Text), _PORT));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(AcceptCallback, null);
}
void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
socket = _serverSocket.EndAccept(AR);
}
catch
{
MessageBox.Show("Not Working!");
return;
}
_clientSockets.Add(socket);
int id = _clientSockets.Count - 1;
IPAddress ip = IPAddress.Parse(_serverSocket.LocalEndPoint.ToString().Split(':')[0]);
string HostName = Dns.GetHostEntry(ip).HostName.Split('.')[0];
string finalName = HostName + " (" + ip.ToString() + ")";
AddClientForSelectionCallback(finalName);
}
This is the send function.
byte[] postBuffer = Encoding.ASCII.GetBytes("Sending Complete!");
void Send(string filePath)
{
try
{
_serverSocket.SendFile(filePath, null, postBuffer, TransmitFileOptions.ReuseSocket);
}
catch (Exception ec)
{
MessageBox.Show("Failed with error message:\n "+ ec);
}
}
Lastly, how would Receive the file sent because _newSocket.Receive() does not seem to work. I have looked at storing its result in a var, but Receive returns nothing and I will try using ConnectAsync.
Help would really be appreciated.
In your program, _serverSocket is the socket that accepts incoming connections, you cannot send data to it.
As soon as a connection is accepted, you get the socket for that connection:
socket = _serverSocket.EndAccept(AR);
You can use this socket instance to communicate with that specific client.
I wrote a server-client chat LAN app for windows PC using class TcpClient. It worked then I wanted to put Client app chat on android thanks to xamarin,
to connect PC and mobile.
Connecting process works:
private void buttonClickConnect(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.1.1"), int.Parse("13000"));
try
{
client.Connect(IP_End);
if (client.Connected)
{
textviewConversation.Text += "Connected to server" + "\n";
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
worker1.RunWorkerAsync();
worker2.WorkerSupportsCancellation = true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
it connects to the server, but I cannot send messages. After the second message app crashes, it reads that thread is busy.
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine(text_to_send);
}
else
{
Console.WriteLine("send failed !");
}
worker2.CancelAsync();
}
There is no loop and the thread should just send it and and not block afterwards.
Find the full code here.
I'm developing a server application where clients need to connect to.
But I don't want my users to enter an IP address... i want the Client to discover all servers running on port 4800 (in my case)
Here's my Server Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static ThreadStart ts = new ThreadStart(start_server);
Thread thread = new Thread(ts);
private void Form1_Load(object sender, EventArgs e)
{
thread.Start();
}
private static void start_server()
{
//Start server
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
Console.Write("Running server..." + Environment.NewLine);
server.Bind(new IPEndPoint(IPAddress.Any, 4800));
while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
//Recive message from anyone.
server.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Server got '" + Encoding.ASCII.GetString(buffer).TrimEnd(new char[] { (char)0 }) +
"' from " + tempRemoteEP.ToString() +
Environment.NewLine);
string access_code = Encoding.ASCII.GetString(buffer).TrimEnd(new char[] { (char)0 });
if (access_code == "7uz876t5r798qwe12")
{
Console.Write("Sending Response to " + tempRemoteEP.ToString() +
Environment.NewLine);
//Replay to client
server.SendTo(Encoding.ASCII.GetBytes("ACCESS GRANTED"),
tempRemoteEP);
}
else
{
Console.WriteLine("Client Access denied!");
server.SendTo(Encoding.ASCII.GetBytes("ACCESS DENIED"),
tempRemoteEP);
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Environment.Exit(Environment.ExitCode);
}
}
and thats my client sending a UDP Broadcast:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 4800);
//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//Send message to everyone
client.SendTo(Encoding.ASCII.GetBytes("7uz876t5r798qwe12"), AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);
IPEndPoint _sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)_sender;
byte[] buffer = new byte[1000];
string serverIp;
try
{
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
client.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Client got '" + buffer[0] + "' from " +
tempRemoteEP.ToString() + Environment.NewLine);
MessageBox.Show(Encoding.ASCII.GetString(buffer).TrimEnd(new char[] { (char)0 }));
//Get server IP (ugly)
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
listServer.Items.Add(serverIp);
}
catch (Exception ex)
{
//Timout. No server answered.
MessageBox.Show(ex.Message);
}
// MessageBox.Show(serverIp);
}
}
All Servers running are Receiving the Broadcast, but my Client only receives 1 IP address. Maybe the first response that reaches the client?
How am I able to discover all my Servers listening on my Port?
Your client is calling ReceiveFrom() only once, so it is going to receive only one response. You need to call ReceiveFrom() in a loop instead, and run the loop for several seconds to give multiple servers enough time to respond.
I'm pretty new to this, I just want to send a message from my console server window to the client.
Here's my server:
static void Main(string[] args)
{
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(localEndPoint);
newsock.Listen(10);
Socket client = newsock.Accept();
if (client.Connected)
{
Console.WriteLine("client connected.");
}
string msg = "Who's there?";
byte[] buffer = new byte[msg.Count()];
buffer = Encoding.ASCII.GetBytes(msg);
client.Send(buffer);
It works fine when i use client.Send() above, but when when I do as follows below I receive nothing on the other end. Since the client is connected, I see no reason why it fails.
while (client.Connected)
{
Console.WriteLine("enter msg: ");
string userMsg = Console.ReadLine();
byte[] userBuffer = new byte[userMsg.Count()];
userBuffer = Encoding.ASCII.GetBytes(userMsg);
client.Send(userBuffer);
Console.ReadKey();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
Here's the code for the client:
public partial class MainWindow : Window
{
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);
byte[] buffer = new byte[12];
public MainWindow()
{
InitializeComponent();
}
private void btn_Connect_Click(object sender, RoutedEventArgs e)
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
server.Connect(ipep);
if (server.Connected)
{
txt_Log.AppendText("\nConnected to target server.");
}
btn.IsEnabled = false;
btn_disc.IsEnabled = true;
}
private void btn_Disconnect_Click(object sender, RoutedEventArgs e)
{
server.Close();
if (!server.Connected)
{
txt_Log.AppendText("\nDisconnected to target server.");
}
btn.IsEnabled = true;
btn_disc.IsEnabled = false;
}
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
using (server)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
}
Well I've run your server code. No problems there...
For the client, it seemed you dispose the server, which drops the connnection? and null the buffer, so you can't re-use that either....
I wrote some test client code which seemed to work fine
class Program
{
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect("127.0.0.1", 8000);
byte[] buffer = new byte[1024];
while (true)
{
int bytes = server.Receive(buffer);
Console.WriteLine(System.Text.Encoding.Default.GetString(buffer, 0, bytes));
}
}
}
Note that the point of this you don't disconnect the client every time you read a packet, and if you null your static before and then null check it is going to be null so fetch will only work once, therefore don't do it!
Also as Mark said, check the number of bytes read from the call the Receive so you can tell how many bytes to decode.
Change
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
using (server)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
To..
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
and call dispose when the window is closed
protected override void OnClosed(EventArgs e) {
base.OnClosed(e);
server.Dispose();
}
My first question here. I am new to this kind of programming, and i've only programmed .NET web sites and forms.
Now, the company I work at, asks me to make an ActiveX component, that listens to UDP messages, and turns them into events.
The UDP msgs are send from Avaya system, so i was told that to test my ActiveX, at first I need to create an app, that only sends UDP (only one button that sends pre-defined UDP string). And then create listener socket, ordinary C# app, that will get those transmitted UDP string from the tests app. Both apps will work on the same machine.
Later, when i get this working, i need to make the listener an ActiveX component, but first things first.
I need to know if there are any good tutorials about this, and any idea on how to start? I am sorry for my ignorance, but i am really new on this and i don't really have any time to learn this since it has to be done in 2 weeks.
Thanks in advance.
edit: I managed to create 2 simple console applications, and was sending UDP messages between them successfully. The sender will be only for testing, and now I need to re-make my receiver to get the UDP message and 'translate' it to events. And lastly, to make it an ActiveX control...
Simple server and client:
public struct Received
{
public IPEndPoint Sender;
public string Message;
}
abstract class UdpBase
{
protected UdpClient Client;
protected UdpBase()
{
Client = new UdpClient();
}
public async Task<Received> Receive()
{
var result = await Client.ReceiveAsync();
return new Received()
{
Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length),
Sender = result.RemoteEndPoint
};
}
}
//Server
class UdpListener : UdpBase
{
private IPEndPoint _listenOn;
public UdpListener() : this(new IPEndPoint(IPAddress.Any,32123))
{
}
public UdpListener(IPEndPoint endpoint)
{
_listenOn = endpoint;
Client = new UdpClient(_listenOn);
}
public void Reply(string message,IPEndPoint endpoint)
{
var datagram = Encoding.ASCII.GetBytes(message);
Client.Send(datagram, datagram.Length,endpoint);
}
}
//Client
class UdpUser : UdpBase
{
private UdpUser(){}
public static UdpUser ConnectTo(string hostname, int port)
{
var connection = new UdpUser();
connection.Client.Connect(hostname, port);
return connection;
}
public void Send(string message)
{
var datagram = Encoding.ASCII.GetBytes(message);
Client.Send(datagram, datagram.Length);
}
}
class Program
{
static void Main(string[] args)
{
//create a new server
var server = new UdpListener();
//start listening for messages and copy the messages back to the client
Task.Factory.StartNew(async () => {
while (true)
{
var received = await server.Receive();
server.Reply("copy " + received.Message, received.Sender);
if (received.Message == "quit")
break;
}
});
//create a new client
var client = UdpUser.ConnectTo("127.0.0.1", 32123);
//wait for reply messages from server and send them to console
Task.Factory.StartNew(async () => {
while (true)
{
try
{
var received = await client.Receive();
Console.WriteLine(received.Message);
if (received.Message.Contains("quit"))
break;
}
catch (Exception ex)
{
Debug.Write(ex);
}
}
});
//type ahead :-)
string read;
do
{
read = Console.ReadLine();
client.Send(read);
} while (read != "quit");
}
}
Simple server and client:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
// Create UDP client
int receiverPort = 20000;
UdpClient receiver = new UdpClient(receiverPort);
// Display some information
Console.WriteLine("Starting Upd receiving on port: " + receiverPort);
Console.WriteLine("Press any key to quit.");
Console.WriteLine("-------------------------------\n");
// Start async receiving
receiver.BeginReceive(DataReceived, receiver);
// Send some test messages
using (UdpClient sender1 = new UdpClient(19999))
sender1.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);
using (UdpClient sender2 = new UdpClient(20001))
sender2.Send(Encoding.ASCII.GetBytes("Hi!"), 3, "localhost", receiverPort);
// Wait for any key to terminate application
Console.ReadKey();
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
// Convert data to ASCII and print in console
string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine);
// Restart listening for udp data packages
c.BeginReceive(DataReceived, ar.AsyncState);
}
}
Server
public void serverThread()
{
UdpClient udpClient = new UdpClient(8080);
while(true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
lbConnections.Items.Add(RemoteIpEndPoint.Address.ToString()
+ ":" + returnData.ToString());
}
}
And initialize the thread
private void Form1_Load(object sender, System.EventArgs e)
{
Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
thdUDPServer.Start();
}
Client
private void button1_Click(object sender, System.EventArgs e)
{
UdpClient udpClient = new UdpClient();
udpClient.Connect(txtbHost.Text, 8080);
Byte[] senddata = Encoding.ASCII.GetBytes("Hello World");
udpClient.Send(senddata, senddata.Length);
}
Insert it to button command.
Source: http://technotif.com/creating-simple-udp-server-client-transfer-data-using-c-vb-net/