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
Related
I'm going to create a socket to send a string from console application server to AndroidWearable client. I use Visual Studio Xamarin, and I never use XML Language. When I click the button nothing happens, How can I improve my program?
Part MainActivity.cs
using Android.App;
using Android.OS;
using Android.Support.Wearable.Activity;
using Android.Views;
using Android.Widget;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace AndroidClient
{
[Activity(Label = "#string/app_name", MainLauncher = true)]
public class MainActivity : WearableActivity
{
private TextView textView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
textView = FindViewById<TextView>(Resource.Id.text);
SetAmbientEnabled();
}
/** Called when the user touches the button */
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public void mainsendMessage(View view)
{
// Do something in response to button click
StartListening();
}
}
}
Part AXML-Origin
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
Server C#
SERVER
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server_microsoft
{
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf(data) > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
}
Thanks!
For example I have to inser some TextView o see the string? How can I make this or one button is necessary?
I have a problem with connection handling in TCP Client socket.
This code should connect to localhost at 4444 port and listening for all incoming data from this TCP Server.
I need to write connection handling for this. For example if while attempting to connect server is not responding it should trying to connect again, or if connection is ready and after receiving some data TCP server will close the connection TCP client should try to reconnect again.
Can anyone help me with this problems
Here is what I have in this moment
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
public class TCPClientNew : MonoBehaviour {
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[8142];
private void StartClient()
{
try
{
_clientSocket.Connect(new IPEndPoint(IPAddress.Loopback,4444));
}
catch(SocketException ex)
{
Debug.Log(ex.Message);
// Try to reconnect ?? TODO
}
Debug.Log ("connected");
_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
private void ReceiveCallback(IAsyncResult AR)
{
//Check how much bytes are recieved and call EndRecieve to finalize handshake
int recieved = _clientSocket.EndReceive(AR);
if(recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer,0,recData,0,recieved);
//Processing received data
Debug.Log (System.Text.Encoding.ASCII.GetString(recData));
//Start receiving again
_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
private void SendData(byte[] data)
{
SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
socketAsyncData.SetBuffer(data,0,data.Length);
_clientSocket.SendAsync(socketAsyncData);
}
void Start()
{
StartClient ();
}
}
What you want is a way to keep retrying the connection if it fails. And if there is an exception during a read, you want to see if we're still connect and if not then re-connect. I added a loop in the Connect() method to retry the connect after waiting for 1 second.
In the receive callback, I put a try/catch and if there is an exception I will go back to the Connect() method to retry the connection.
public class TCPClientNew
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[8142];
private void Connect()
{
bool isConnected = false;
// Keep trying to connect
while (!isConnected)
{
try
{
_clientSocket.Connect(new IPEndPoint(IPAddress.Loopback, 4444));
// If we got here without an exception we should be connected to the server
isConnected = true;
}
catch (SocketException ex)
{
Debug.Log(ex.Message);
// Wait 1 second before trying to connect again
Thread.Sleep(1000);
}
}
// We are now connected, start to receive
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
//Check how much bytes are recieved and call EndRecieve to finalize handshake
try
{
int recieved = _clientSocket.EndReceive(AR);
if (recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved);
//Start receiving again
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (SocketException ex)
{
Debug.Log(ex.Message);
// If the socket connection was lost, we need to reconnect
if (!_clientSocket.Connected)
{
Connect();
}
else
{
//Just a read error, we are still connected
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
}
}
private void SendData(byte[] data)
{
SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
socketAsyncData.SetBuffer(data, 0, data.Length);
_clientSocket.SendAsync(socketAsyncData);
}
}
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
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.
I'm using .NET synchronous socket to send data from a client to server.
I need to get the data from the StartListening() method to use it in the Main() but
the variable data is inside an infinite loop ( while(true)).
Any help please?
This is the server code :
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo;
IPAddress ipAddress ;
IPEndPoint localEndPoint;
Socket listener;
// Incoming data from the client.
public static string data = null;
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
public void InitializeListening()
{
// Data buffer for incoming data.
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
ipHostInfo = Dns.Resolve("localhost");
ipAddress = ipHostInfo.AddressList[0];
localEndPoint = new IPEndPoint(ipAddress, 11007);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
}
public void StopListening()
{
_shouldStop = true;
byte[] msg = Encoding.ASCII.GetBytes("please stop!");
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(localEndPoint);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
public void StartListening()
{
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Thread is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
// An incoming connection needs to be processed.
if (_shouldStop)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
break;
}
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
byte[] msg = Encoding.ASCII.GetBytes("Salam !");
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
Console.WriteLine("I am the Synchronous Socket Server\n");
SynchronousSocketListener pServer = new SynchronousSocketListener();
pServer.InitializeListening();
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
Console.WriteLine("listening thread sevice started...\n");
Console.WriteLine("\nPress Q when you want to quit...\n");
int car;
do
{
Thread.Sleep(100);
car = Console.Read();
if (car == 81)
{
// Request that the worker thread stop itself:
pServer.StopListening();
// Use the Join method to block the current process
// until the object's thread terminates.
serverkerThread.Join();
break;
}
} while (true);
Console.WriteLine("listening thread sevice stopped and program will be exited...\n");
return 0;
}
}
The received data (given it is an ASCII-string ending with "EOF") is stored in the public member named "data" of your pServer object, you can access it like this:
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
string receivedString = pServer.data; // <<--- here we get the received string
Console.WriteLine("listening thread sevice started...\n");