Socket Programming - A connection attempt failed Exception - c#

Am new to socket programming and am creating a chat application.As like other applications whenever i press enter in a chat window it should send the chat to a particular user.Am maintaining a DB for all users along with their IPAddresses.So whenever i select a user for sending chat it should send to the corresponding IPAddress.As of now am trying to send chat to my own machine(so i hard coded the IPAddress of my machine).But am getting an exception when i try to send my code to my IPAddress.Can anyone please help me out.
My code for socket programming is this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace Ping
{
class SocketProgramming
{
//Socket m_socWorker;
public AsyncCallback pfnWorkerCallBack;
public Socket m_socListener;
public Socket m_socWorker;
public void sendChat(IPAddress toMessengerIP)
{
try
{
//create a new client socket ...
m_socWorker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
String szIPSelected = toMessengerIP.ToString();
String szPort = "7777";
int alPort = System.Convert.ToInt16(szPort, 10);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
// receive();
m_socWorker.Connect(remoteEndPoint);
//Send data
Object objData =(object)"hi dhivi";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
m_socWorker.Send(byData);
}
catch (System.Net.Sockets.SocketException se)
{
//MessageBox.Show(se.Message);
Console.Out.Write(se.Message);
}
}
public void receive()
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 7777);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
//cmdListen.Enabled = false;
}
catch (SocketException se)
{
Console.Out.Write(se.Message);
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept(asyn);
WaitForData(m_socWorker);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
Console.Out.Write(se.Message);
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
//if (pfnWorkerCallBack == null)
//{
// pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
//}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
Console.Out.Write(se.Message);
}
}
}
}
And whenever the users clicks the enter button it should call the sendChat() method.
private void txt_Userinput_KeyDown_1(object sender, KeyEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
TabItem tb = (TabItem)this.Parent;
string user = tb.Header.ToString();
if (e.Key == Key.Return)
{
richtxtbox_chatwindow.AppendText(Environment.NewLine + user + " : " + txt_Userinput.Text);
DBCoding dbObject = new DBCoding();
SocketProgramming socketObj = new SocketProgramming();
socketObj.sendChat(IPAddress.Parse("192.168.15.41"));
}
else { return; }
}
To get ipaddress of the user
public IPAddress getIP()
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
IPAddress ip = IPAddress.Parse(direction);
return ip;
}

You never seem to be calling your receive method. If your application never starts listening, no one will ever be able to connect. If you've tried that, and is getting an exception, post that and we'll go from there.

Related

C# TCP Application won't work

I'm making a simple chat application using TcpClient and TcpServer from System.Net.
I got everything working on my PC, the server communicates with the client and vice versa. But when I try to connect to the same server application using another PC (even on the same subnet as my PC) the thing doesn't work.
I've tried port-forwarding through my router, firewall and still nothing.
The Can you see me website says that the connection is being refused. Although!! Sometimes it says that the connection is timed out completely.
I am not sure what's wrong with my code or my PC, I would really appreciate some help from people that are more experienced in this area than I am.
Here is the configuration for the port forwarding in my router:
If you need the code for the client and the server, here they are:
P.S. I make the change to the client in the BeginConnect() part at the bottom in order to change the IP address that I'm connecting to
Client:
using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace TcpTest_Client_
{
public partial class Form1 : Form
{
TcpClient client;
IPAddress localIP = null;
bool connected = false;
public Form1()
{
InitializeComponent();
}
public void clientConnectCallback(IAsyncResult result)
{
try
{
client.EndConnect(result);
Log("Connected to " + client.Client.RemoteEndPoint);
connected = true;
NetworkStream clientStream = client.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Log(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
Log("Server on has disconnected");
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
string bufferincmessage = encoder.GetString(message, 0, bytesRead);
Log("Server: " + bufferincmessage);
}
}
catch (Exception ex)
{
Log(ex.Message);
}
}
public void Log(string msg)
{
richTextBox1.BeginInvoke(new Action(
() =>
{
richTextBox1.Text += msg + "\n";
}));
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
localIP = addr;
break;
}
}
client = new TcpClient(AddressFamily.InterNetwork);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
client.BeginConnect(IPAddress.Parse("109.252.107.144"), 1234, clientConnectCallback, client);
}
catch (Exception ex)
{
Log(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (connected)
{
UTF8Encoding encoder = new UTF8Encoding();
NetworkStream clientStream = client.GetStream();
byte[] stringToSend = new byte[richTextBox2.Text.Length];
stringToSend = encoder.GetBytes(richTextBox2.Text);
clientStream.Write(stringToSend, 0, stringToSend.Length);
}
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TcpTest
{
public partial class Form1 : Form
{
private TcpListener server;
private List<Thread> clientThreads = null;
public Thread MainThread;
public Form1()
{
InitializeComponent();
}
public void Log(string msg)
{
richTextBox1.BeginInvoke(new Action(
() =>
{
richTextBox1.Text += msg + "\n";
}));
}
public static string bufferincmessage;
public void AcceptSocketPackets(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Log(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
Log("Client on " + tcpClient.Client.RemoteEndPoint + " has disconnected from the server");
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
bufferincmessage = encoder.GetString(message, 0, bytesRead);
Log("Client from " + tcpClient.Client.RemoteEndPoint + ": " + bufferincmessage);
string stringToSend = "You sent me: " + bufferincmessage;
byte[] messageToSend = new byte[stringToSend.Length];
messageToSend = encoder.GetBytes(stringToSend);
clientStream.Write(messageToSend, 0, messageToSend.Length);
}
}
public void SocketAcceptCallback(IAsyncResult result)
{
TcpClient newClient = server.EndAcceptTcpClient(result);
Log("Accepted client on " + newClient.Client.RemoteEndPoint);
clientThreads.Add(new Thread(new ParameterizedThreadStart(AcceptSocketPackets)));
clientThreads[clientThreads.Count - 1].Start(newClient);
server.BeginAcceptTcpClient(SocketAcceptCallback, server);
}
private void Form1_Load(object sender, EventArgs e)
{
MainThread = Thread.CurrentThread;
clientThreads = new List<Thread>();
try
{
IPAddress localIP = null;
foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
localIP = addr;
break;
}
}
localIP = IPAddress.Any;
// could also use this:
// server = new TcpListener(new IPEndPoint(IPAddress.Any, 1234));
server = new TcpListener(new IPEndPoint(localIP, 1234));
Log("Starting server on " + localIP + ":1234");
server.Start(6);
server.BeginAcceptTcpClient(SocketAcceptCallback, server);
Log("Started server on " + localIP + ":1234");
}
catch (Exception ex)
{
Log(ex.Message);
}
}
}
}
C++ is giving me problems like that. Try creating another project, paste the server code and build it as Release x86. If you change the build target and our problem is the same, windows firewall, even when turned off, won't allow the server or the client to run without any exception. If it doesn't work I might not know the answer.

data from gps sometimes changed to unreadable format

I am getting data from avl system as you can see with this format :
*HQ,4106016320,V1,090458,A,5257.4318,N,15840.4221,E,000.00,000,101115,FFFFFBFF,250,01,0,0,5#
As you can see the data that i get from the gps is :
As you can see in some lines the data is unreadable .why this problem happened?
My server that gets the data is like this :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace smartparckingHandlerServer
{
public partial class Form1 : Form
{
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[25];
private int m_clientCount = 0;
private string ipaddress;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
startfun();
}
public void startfun()
{
try
{
// DrawMapPersian();
ipaddress = "127.0.0.1";
// Check the port value
string portStr = "5000";
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);
listBox1.Items.Add("Server Started...");
// Start listening...
m_mainSocket.Listen(20);
listBox1.Items.Add("Server Listening for ...");
// Create the call back for any client connections...
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (Exception qqq)
{
using (StreamWriter writer =
new StreamWriter(#"f:\a.txt"))
{
writer.Write(qqq.Message);
}
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
// Here we complete/end the BeginAccept() asynchronous call
// by calling EndAccept() - which returns the reference to
// a new Socket object
m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
// Let the worker Socket do the further processing for the
// just connected client
WaitForData(m_workerSocket[m_clientCount]);
// Now increment the client count
++m_clientCount;
// Display this client connection as a status message on the GUI
String str = String.Format("Client # {0} connected", m_clientCount);
// Since the main Socket is now free, it can go back and wait for
// other clients who are attempting to connect
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
using (StreamWriter writer =
new StreamWriter(#"f:\con.txt"))
{
writer.Write("connect to client");
}
}
catch (Exception qqq)
{
using (StreamWriter writer =
new StreamWriter(#"f:\a.txt"))
{
writer.Write(qqq.Message);
}
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
public byte[] dataBuffer = new byte[200];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
// Specify the call back function which is to be
// invoked when there is any write activity by the
// connected client
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.m_currentSocket = soc;
// Start receiving any data written by the connected client
// asynchronously
soc.BeginReceive(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
pfnWorkerCallBack,
theSocPkt);
}
catch (Exception qqq)
{
using (StreamWriter writer =
new StreamWriter(#"f:\a.txt"))
{
writer.Write(qqq.Message);
}
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
iRx = socketData.m_currentSocket.EndReceive(asyn);
string res = GetParameters(socketData.dataBuffer);
Console.WriteLine(res.ToString());
//char[] chars = new char[iRx + 1];
//System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
//int charLen = d.GetChars(socketData.dataBuffer,
// 0, iRx, chars, 0);
//System.String szData = new System.String(chars);
this.Invoke(new MethodInvoker(delegate ()
{
listBox1.Items.Add("clinet's data:" + res);
}));
// Continue the waiting for data on the Socket
WaitForData(socketData.m_currentSocket);
//socketData = null;
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
}
catch (Exception qqq)
{
using (StreamWriter writer =
new StreamWriter(#"f:\a.txt"))
{
writer.Write(qqq.Message);
}
}
}
public string GetParameters(byte[] buf)
{
string result = System.Text.Encoding.ASCII.GetString(buf);
return result;
}
}
}
when i move the GPS it returns unreadable data.why?
It's a longshot, but try changing
string result = System.Text.Encoding.ASCII.GetString(buf);
to
string result = System.Text.Encoding.UTF8.GetString(buf);
or
string result = System.Text.Encoding.Default.GetString(buf);

How to make server client autodiscover over a lan

I have two project "Server" and "Client" that communicate over a LAN,
this my server code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ServerClientProject
{
public partial class FormServer : Form
{
private static Int32 port;
private static string filePath;
TcpListener server = new TcpListener(IPAddress.Any, port);
public FormServer()
{
InitializeComponent();
}
private void FormServer_Load(object sender, EventArgs e)
{
File.WriteAllText("path.misc","");
File.WriteAllText("nama.misc","");
filePath = readPath();
label1.Text = filePath;
label2.Text = readNama();
label3.Text = IPAddressCheck();
label4.Text = UNCPathing.GetUNCPath(readPath());
label5.Text = GetFQDN();
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private static string IPAddressCheck()
{
IPHostEntry IPAddr;
IPAddr = Dns.GetHostEntry(GetFQDN());
IPAddress ipString = null;
foreach (IPAddress ip in IPAddr.AddressList)
{
if (IPAddress.TryParse(ip.ToString(), out ipString) && ip.AddressFamily == AddressFamily.InterNetwork)
{
break;
}
}
return ipString.ToString();
}
public static string GetFQDN()
{
string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
if (!hostName.EndsWith(domainName)) // if hostname does not already include domain name
{
hostName += "." + domainName; // add the domain name part
}
return hostName; // return the fully qualified name
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lstProgress.Items.Add(e.UserState);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
try
{
// Set the TcpListener on port 1333.
port = 1337;
//IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(IPAddress.Any, port);
//label2.Text = IPAddressToString(ip);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
bw.ReportProgress(0, "Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
bw.ReportProgress(0, "Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
bw.ReportProgress(0, String.Format("Received: {0}", data));
if (data == "file")
{
// Process the data sent by the client.
data = String.Format("Request: {0}", data);
byte[] mssg = System.Text.Encoding.ASCII.GetBytes(label4.Text);
// Send back a response.
stream.Write(mssg, 0, mssg.Length);
bw.ReportProgress(0, String.Format("Sent: {0}", data));
bw.ReportProgress(0, String.Format("File path : {0}", label4.Text));
}
else if (data == "nama")
{
byte[] mssg = System.Text.Encoding.ASCII.GetBytes(readNama());
stream.Write(mssg, 0, mssg.Length);
}
else if (data == "ip")
{
byte[] mssg = System.Text.Encoding.ASCII.GetBytes(GetFQDN());
stream.Write(mssg, 0, mssg.Length);
}
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException se)
{
bw.ReportProgress(0, String.Format("SocketException: {0}", se));
}
}
}
private void FormServer_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
savePath(openFileDialog1.FileName.ToString());
saveNama(openFileDialog1.SafeFileName.ToString());
//folderBrowserDialog1.ShowDialog();
//savePath(folderBrowserDialog1.SelectedPath.ToString());
label1.Text = readPath();
label2.Text = readNama();
label4.Text = UNCPathing.GetUNCPath(readPath());
}
private void savePath(string fPath)
{
string sPath = "Path.misc";
File.WriteAllText(sPath, fPath);
}
private string readPath()
{
string readText = File.ReadAllText("Path.misc");
return readText;
}
private void saveNama(string nama)
{
string sNama = "Nama.misc";
File.WriteAllText(sNama, nama);
}
private string readNama()
{
string readText = File.ReadAllText("Nama.misc");
return readText;
}
}
}
and this my client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class FormClient : Form
{
public FormClient()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = IPAddressCheck();
label2.Text = GetFQDN();
label3.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
public void msg(string mesg)
{
lstProgress.Items.Add(">> " + mesg);
}
public static string GetFQDN()
{
string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
if (!hostName.EndsWith(domainName)) // if hostname does not already include domain name
{
hostName += "." + domainName; // add the domain name part
}
return hostName; // return the fully qualified name
}
private static string IPAddressCheck()
{
IPHostEntry IPAddr;
IPAddr = Dns.GetHostEntry(GetFQDN());
IPAddress ipString = null;
foreach (IPAddress ip in IPAddr.AddressList)
{
if (IPAddress.TryParse(ip.ToString(), out ipString) && ip.AddressFamily == AddressFamily.InterNetwork)
{
break;
}
}
return ipString.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string message = textBox1.Text;
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 1337;
string IPAddr = textBox2.Text;
TcpClient client = new TcpClient(IPAddr, port); //Unsure of IP to use.
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//lstProgress.Items.Add(String.Format("Sent: {0}", message));
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
if (message == "file")
{
lstProgress.Items.Add(String.Format("{0}", responseData));
fPath.getPath = (String.Format("{0}", responseData));
label4.Text = UNCPathing.GetUNCPath(fPath.getPath);
}
else if(message == "nama")
{
lstProgress.Items.Add(String.Format("{0}", responseData));
fPath.getNama = (String.Format("{0}", responseData));
}
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException an)
{
lstProgress.Items.Add(String.Format("ArgumentNullException: {0}", an));
}
catch (SocketException se)
{
lstProgress.Items.Add(String.Format("SocketException: {0}", se));
}
}
private void button2_Click(object sender, EventArgs e)
{
//using (NetworkShareAccesser.Access(GetFQDN(), IPAddressCheck(), "arif.hidayatullah28#gmail.com", "971364825135win8"))
//{
// File.Copy("\\\\"+label1.Text+"\\TestFolder\\"+fPath.getNama+"", #"D:\movie\"+ fPath.getNama+"", true);
//}
}
private void button3_Click(object sender, EventArgs e)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ARIF-PC\aaaaaaaaaa\MsAccess.accdb; Jet OLEDB:Database Password=dbase;";
string cmdText = "SELECT kode, deskripsi, stok, Harga FROM [Barang] ORDER BY kode DESC";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
try
{
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable barang = new DataTable();
da.Fill(barang);
dataGridView1.DataSource = barang;
}
finally
{
conn.Close();
}
}
}
}
but as you can see, I have to know the server ip address, is there a way to make the server and client autodiscover??
I've try this, worked with one PC but with a LAN it failed.
This that I've tried
Sorry form my bad English
On the client send a UDP broadcast 192.168.1.255 (this assumes you are operating on a class C network 192.168.1/24). The server then listens for the broadcast from any clients and then sends back a directed UDP packet to the client. The client is listening for this and decodes the packet which contains the address of the server.
This link C# How to do Network discovery using UDP Broadcast and some Google Fu will produce many examples of how to implement this.

C# socket just first message received

I have searched many examples and tutorials and what not but I cant for the life of me figure out what im doing wrong here... If I send several messages to this server I made only the first is printed in the Console.Writeline command and the rest is never printed... I must be doing something fundametally wrong but I really cant find it ... :S
This is the server code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms.VisualStyles;
namespace HL7_Manager
{
public class MonitorServer
{
private int _port;
private Socket _serverSocket;
private List<ClientObject> _clients;
public bool IsConnected { get; set; }
public MonitorServer(int port)
{
_port = port;
_clients = new List<ClientObject>();
}
public void StartListening()
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Thread listenThread = new Thread(new ThreadStart(ListenerThread));
listenThread.IsBackground = true;
listenThread.Start();
}
public void StopListening()
{
IsConnected = true;
_serverSocket.Close();
while (_clients.Count > 0)
{
_clients[0].KeepProcessing = false;
_clients[0].ClientSocket.Close();
_clients.RemoveAt(0);
}
}
private void ListenerThread()
{
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, _port));
_serverSocket.Listen(100);
Console.WriteLine("Listening on port 8000");
while (true)
{
Socket clientSocket = _serverSocket.Accept();
ClientObject client = new ClientObject();
client.KeepProcessing = true;
client.ClientSocket = clientSocket;
_clients.Add(client);
ParameterizedThreadStart ptStart = new ParameterizedThreadStart(ProcessClientThread);
Thread processThread = new Thread(ptStart);
processThread.IsBackground = true;
processThread.Start(client);
clientSocket = null;
client = null;
}
}
private void ProcessClientThread(object clientObj)
{
Console.WriteLine("Client connected");
ClientObject client = (ClientObject) clientObj;
Socket clientSocket = client.ClientSocket;
byte[] buffer = new byte[clientSocket.ReceiveBufferSize];
int receiveCount = 0;
while (client.KeepProcessing)
{
try
{
receiveCount = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
Console.WriteLine(Encoding.ASCII.GetString(buffer));
}
catch (Exception ex)
{
if (!client.KeepProcessing)
return;
Console.WriteLine(ex.Message);
}
}
clientSocket.Close();
_clients.Remove(client);
}
}
}
Here is the method you should definitely change and how to change it.
private void ProcessClientThread(object clientObj)
{
Console.WriteLine("Client connected");
ClientObject client = (ClientObject)clientObj;
Socket clientSocket = client.ClientSocket;
byte[] buffer = new byte[clientSocket.ReceiveBufferSize];
int receiveCount = 0;
while (client.KeepProcessing)
{
try
{
receiveCount = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
if (receiveCount == 0)
break; //the client has closed the stream
var ret = Encoding.ASCII.GetString(buffer, 0, receiveCount);
Console.WriteLine(ret);
}
catch (Exception ex)
{
if (!client.KeepProcessing)
return;
Console.WriteLine(ex.Message);
}
}
clientSocket.Close();
_clients.Remove(client);
}
Check how many bytes you really received.
TCP is a streaming protocol this means that if you client is doing several sends of small messages right one after the other, you will receive them in one go at the receiver.
If there happens to be a null character in your receive buffer you might think you did not receive all those string, but actually you did.
Check this by inspecting how many bytes you received and by checking the buffer content.
If you made this mistake there might be some deeper problem in your code. The fact that TCP is streaming makes it a bit more complex

C# socket datagram overflow

I'm new in c# =)
I have a litle question about udp socket.
I have a chat server that receives packets to a specific structure (udp datagram).
Why program receives data when the socket buffer is full? Does all that come after should not be be lost? Maybe packet fragmentation occurs?
Packet structure : udp_headers(28 byte)| dataIdentifier ( 4 byte)|name length(4 byte)|mesage length (4 bytes)|name(name length)|message(message length)
When I send a packet larger than the internal buffer. The program throws an exception:
ReceiveData Error: A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself
All I need is to drop such packets before they cause this error. Is it possible?
Server code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using ChatApplication;
namespace ChatServer
{
public partial class Server : Form
{
#region Private Members
// Structure to store the client information
private struct Client
{
public EndPoint endPoint;
public string name;
}
// Listing of clients
private ArrayList clientList;
// Server socket
private Socket serverSocket;
// Data stream
private byte[] dataStream = new byte[1024];
// Status delegate
private delegate void UpdateStatusDelegate(string status);
private UpdateStatusDelegate updateStatusDelegate = null;
#endregion
#region Constructor
public Server()
{
InitializeComponent();
}
#endregion
#region Events
private void Server_Load(object sender, EventArgs e)
{
try
{
// Initialise the ArrayList of connected clients
this.clientList = new ArrayList();
// Initialise the delegate which updates the status
this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
// Initialise the socket
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Initialise the IPEndPoint for the server and listen on port 30000
IPEndPoint server = new IPEndPoint(IPAddress.Any, 30000);
// Associate the socket with this IP address and port
serverSocket.Bind(server);
// Initialise the IPEndPoint for the clients
IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
// Initialise the EndPoint for the clients
EndPoint epSender = (EndPoint)clients;
// Start listening for incoming data
serverSocket.BeginReceiveFrom(this.dataStream, 0, 1024, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);
lblStatus.Text = "Listening";
}
catch (Exception ex)
{
lblStatus.Text = "Error";
MessageBox.Show("Load Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
#endregion
#region Send And Receive
public void SendData(IAsyncResult asyncResult)
{
try
{
serverSocket.EndSend(asyncResult);
}
catch (Exception ex)
{
MessageBox.Show("SendData Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ReceiveData(IAsyncResult asyncResult)
{
try
{
byte[] data;
// Initialise a packet object to store the received data
Packet receivedData = new Packet(this.dataStream);
// Initialise a packet object to store the data to be sent
Packet sendData = new Packet();
// Initialise the IPEndPoint for the clients
IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
// Initialise the EndPoint for the clients
EndPoint epSender = (EndPoint)clients;
// Receive all data
serverSocket.EndReceiveFrom(asyncResult, ref epSender);
// Start populating the packet to be sent
sendData.ChatDataIdentifier = receivedData.ChatDataIdentifier;
sendData.ChatName = receivedData.ChatName;
switch (receivedData.ChatDataIdentifier)
{
case DataIdentifier.Message:
sendData.ChatMessage = string.Format("{0}: {1}", receivedData.ChatName, receivedData.ChatMessage);
break;
case DataIdentifier.LogIn:
// Populate client object
Client client = new Client();
client.endPoint = epSender;
client.name = receivedData.ChatName;
// Add client to list
this.clientList.Add(client);
sendData.ChatMessage = string.Format("-- {0} is online --", receivedData.ChatName);
break;
case DataIdentifier.LogOut:
// Remove current client from list
foreach (Client c in this.clientList)
{
if (c.endPoint.Equals(epSender))
{
this.clientList.Remove(c);
break;
}
}
sendData.ChatMessage = string.Format("-- {0} has gone offline --", receivedData.ChatName);
break;
}
// Get packet as byte array
data = sendData.GetDataStream();
foreach (Client client in this.clientList)
{
if (client.endPoint != epSender || sendData.ChatDataIdentifier != DataIdentifier.LogIn)
{
// Broadcast to all logged on users
serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, client.endPoint, new AsyncCallback(this.SendData), client.endPoint);
}
}
// Listen for more connections again...
serverSocket.BeginReceiveFrom(this.dataStream, 0, 1024, SocketFlags.None, ref epSender, new AsyncCallback(this.ReceiveData), epSender);
// Update status through a delegate
this.Invoke(this.updateStatusDelegate, new object[] { sendData.ChatMessage });
}
catch (Exception ex)
{
MessageBox.Show("ReceiveData Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Other Methods
private void UpdateStatus(string status)
{
rtxtStatus.Text += status + Environment.NewLine;
}
#endregion
}
}
This is udp sender and reciver in one . Use /s if you want listen
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPTestClient
{
class Program
{
static void RecvCompleted(object sender, SocketAsyncEventArgs e)
{
string Data = Encoding.ASCII.GetString(e.Buffer, e.Offset, e.BytesTransferred);
e.Dispose();
ReceiveUdp((Socket)e.UserToken);
Console.WriteLine(Data);
}
static void SendCompleted(object sender, SocketAsyncEventArgs e)
{
int i = e.Count;
e.Dispose();
Console.WriteLine("{0} bytes send", i);
}
static void ReceiveUdp(Socket s)
{
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
//set buffer to 100 .Now it's work fine.
e.SetBuffer(new byte[100], 0, 100);
e.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
e.UserToken = s;
e.Completed += new EventHandler<SocketAsyncEventArgs>(RecvCompleted);
s.ReceiveFromAsync(e);
}
static void SendUdp(Socket s, string Data)
{
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
byte[] buf = Encoding.ASCII.GetBytes(Data);
e.SetBuffer(buf, 0, buf.Length);
e.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3333);
e.UserToken = s;
e.Completed += new EventHandler<SocketAsyncEventArgs>(SendCompleted);
s.SendToAsync(e);
}
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
if (args.Length != 0 && args[0] == "/s")
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 3333);
s.Bind(ip);
ReceiveUdp(s);
}
else
{
SendUdp(s, "Hello!");
}
Console.ReadKey();
s.Close();
}
}
}
UDP is a dumb protocol, as in, it does not actually have any knowledge of size or how to work with this. If you want to handle this before an exception occurs, you need to create a different structure for your communication. I would recommend that you do one of the following:
Use a polling mechanism, where the client requests a single update from the server, with a given size, then ensure that the buffer is large enough for this message.
Simply increase your buffer to the correct size.
Catch the exception and simply discard it, when the buffer overflows, then attempt to reestablish.
Use RecieveAsync to only get parts of the datagram at a time. See
http://msdn.microsoft.com/en-us/library/dxkwh6zw(v=vs.110).aspx

Categories