UDP sending but not receiving - c#

I'm working on creating a UDP socket to send and receive data through the PC and a radio terminal device connected to the PC. I can successfully send the data that I want to send, but when it comes to receiving data sent from the radio device to the PC nothing happens the code just stops at the " Byte[] receiveBytes = receivingUdpClient.Receive(ref ipep); " in the Receive function and nothing happens afterwords. The radio device has an IP address = 192.168.1.191 and Port number = 50000. I've also tried to receive through " Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); " but still nothing the code also stops at this point and nothing happens afterwords. Below is the complete code that I have. Any help would be very appreciated, thanks in advance.
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;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace UDP_Socket
{
public partial class Form1 : Form
{
#region Importand Definitions
public UdpClient udpClient;
public String IPaddress;
public String PortNumber;
public IPEndPoint ipep;
#endregion
private void Form1_Load(object sender, EventArgs e)
{
Connect();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (udpClient.Client.Connected == true)
{
udpClient.Client.Close();
udpClient.Client.Dispose();
}
}
private void Add_Btn_Click(object sender, EventArgs e)
{
RadioCheck();
Receive();
}
void RadioCheck()
{
byte[] data = Encoding.ASCII.GetBytes("at");
udpClient.Send(data , data .Length);
}
void Connect()
{
IPaddress = "192.168.1.191";
PortNumber = "50000";
//Uses a remote endpoint to establish a socket connection.
udpClient = new UdpClient();
IPAddress ipAddress = IPAddress.Parse(IPaddress);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(PortNumber));
ipep = ipEndPoint;
try
{
udpClient.Connect(ipEndPoint);
MessageBox.Show("Successfully connected to: " + ipep.ToString(), "Connection", MessageBoxButtons.OK);
}
catch (SocketException ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("Problem connecting to: " + ipep.ToString(), "Connection", MessageBoxButtons.OK);
}
}
void Receive()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(50000);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref ipep);//RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
ipep.Address.ToString() +
" on their port number " +
ipep.Port.ToString()); //RemoteIpEndPoint
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}

Related

my socket application doesnt connect when i try it on the internet

im programming a socket application using c# (.net framework) but when i try it on the local system or private network it works well but when i try it on two different system using internet (public network) it never connect
its my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SocketPermission me = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);
Socket mes =
new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
Socket des;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iphost = Dns.GetHostEntry("");
IPAddress ipaddr = iphost.AddressList[0];
MessageBox.Show(ipaddr.ToString());
IPEndPoint iep = new IPEndPoint(ipaddr, 44444);
label1.Text = ipaddr.ToString();
mes.Bind(iep);
mes.Listen(4);
des = mes.Accept();
MessageBox.Show("connected");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iphost = Dns.GetHostEntry("");
IPAddress ipaddr = iphost.AddressList[0];
MessageBox.Show(ipaddr.ToString());
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox1.Text), 44444);
mes.Connect(iep);
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
}
}
textbox1 return server ipv6.
im using socket permission to open all ports for tcp .
and ipv6 because its unique .

Tcp .Send Doesn't work after using for the first time

I am UsingClient.Send(Encoding.ASCII.GetBytes(Message)); to send a message to the client, when i tried sending a second message it doesn't give any error so i think it send with no problem but it never reaches the client (127.0.0.1)
Code That Send
public void SendMessage(Socket _Client, string Message)
{
foreach (Socket Client in Clients)
{
IPEndPoint TargetEndPoint = _Client.LocalEndPoint as IPEndPoint;
IPAddress TargetIp = TargetEndPoint.Address;
int TargetPort = TargetEndPoint.Port;
IPEndPoint ClientEndPoint = Client.LocalEndPoint as IPEndPoint;
IPAddress ClientIp = ClientEndPoint.Address;
int ClientPort = ClientEndPoint.Port;
if (TargetIp.ToString() == ClientIp.ToString() && TargetPort == ClientPort)
{
Client.Send(Encoding.ASCII.GetBytes(Message));
//Client.EndSend();
}
}
}
Code That Receive
private void RecivedCallBack(IAsyncResult Result)
{
//Create a int with the Buffer Size
int BufferSize = _Socket.EndReceive(Result);
//Create a new byte array with the Buffer Size
byte[] Packet = new byte[BufferSize];
//Copy Buffer to Packet
Array.Copy(_Buffer, Packet, Packet.Length);
//Handle Packet
PacketHandler.Packet(Encoding.UTF8.GetString(Packet));
//Makes _Buffer a new byte
_Buffer = new byte[1024];
//Get Ready to recive data
_Socket.BeginReceive(_Buffer, 0, _Buffer.Length, SocketFlags.None, RecivedCallBack, null);
}
Code that Handle
public static void Packet(string Message)
{
Console.WriteLine(Message);
switch (Message)
{
case "StartChat":
_ChatForm Start = new _ChatForm();
Start.ShowDialog();
break;
case "StopChat":
_ChatForm._Chat.EndChat();
break;
}
}
TCP is stream based, so your client has no way to know when the message has ended. Either use UDP, implement a way to detect the end of messages (eg send a 4 byte message with the length of the real message, before sending the real message... and read on the client until the whole message has been received), or use a library. I like Hazel: https://github.com/DarkRiftNetworking/Hazel-Networking.
The great thing about Hazel is that it implements reliable UDP. So, if you need to have your "messages" arrive in the order in which they were sent, or if you need guaranteed delivery and receipt of such messages (such as what TCP provides), then you can do so with their reliable UDP implementation.
They will also implement Web Sockets at some point :) Good luck!
A client/server example from the documentation:
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Hazel;
using Hazel.Tcp;
namespace HazelExample
{
class ServerExample
{
static ConnectionListener listener;
public static void Main(string[] args)
{
listener = new TcpConnectionListener(IPAddress.Any, 4296);
listener.NewConnection += NewConnectionHandler;
Console.WriteLine("Starting server!");
listener.Start();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
listener.Close();
}
static void NewConnectionHandler(object sender, NewConnectionEventArgs args)
{
Console.WriteLine("New connection from " + args.Connection.EndPoint.ToString();
args.Connection.DataReceived += DataReceivedHandler;
args.Recycle();
}
private static void DataReceivedHandler(object sender, DataEventArgs args)
{
Connection connection = (Connection)sender;
Console.WriteLine("Received (" + string.Join<byte>(", ", args.Bytes) + ") from " + connection.EndPoint.ToString());
connection.SendBytes(args.Bytes, args.SendOption);
args.Recycle();
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hazel;
using Hazel.Tcp;
namespace HazelExample
{
class ClientExample
{
static Connection connection;
public static void Main(string[] args)
{
NetworkEndPoint endPoint = new NetworkEndPoint("127.0.0.1", 4296);
connection = new TcpConnection(endPoint);
connection.DataReceived += DataReceived;
Console.WriteLine("Connecting!");
connection.Connect();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
connection.Close();
}
}
}

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

Socket Programming - A connection attempt failed Exception

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.

SocketException when connecting to server

I am running both client and server on the same machine.
Does any 1 know the error stated above?
server
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.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Server
{
public partial class Server : Form
{
private Socket connection;
private Thread readThread;
private NetworkStream socketStream;
private BinaryWriter writer;
private BinaryReader reader;
//default constructor
public Server()
{
InitializeComponent();
//create a new thread from server
readThread = new Thread(new ThreadStart(RunServer));
readThread.Start();
}
protected void Server_Closing(object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
//sends the text typed at the server to the client
protected void inputText_KeyDown(object sender, KeyEventArgs e)
{
// send the text to client
try
{
if (e.KeyCode == Keys.Enter && connection != null)
{
writer.Write("Server>>> " + inputText.Text);
displayText.Text +=
"\r\nSERVER>>> " + inputText.Text;
//if user at server enter terminate
//disconnect the connection to the client
if (inputText.Text == "TERMINATE")
connection.Close();
inputText.Clear();
}
}
catch (SocketException)
{
displayText.Text += "\nError writing object";
}
}//inputTextBox_KeyDown
// allow client to connect & display the text it sends
public void RunServer()
{
TcpListener listener;
int counter = 1;
//wait for a client connection & display the text client sends
try
{
//step 1: create TcpListener
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcplistener = new TcpListener(ipAddress, 9000);
//step 2: TcpListener waits for connection request
tcplistener.Start();
//step 3: establish connection upon client request
while (true)
{
displayText.Text = "waiting for connection\r\n";
// accept incoming connection
connection = tcplistener.AcceptSocket();
//create NetworkStream object associated with socket
socketStream = new NetworkStream(connection);
//create objects for transferring data across stream
writer = new BinaryWriter(socketStream);
reader = new BinaryReader(socketStream);
displayText.Text += "Connection " + counter + " received.\r\n ";
//inform client connection was successful
writer.Write("SERVER>>> Connection successful");
inputText.ReadOnly = false;
string theReply = "";
// step 4: read string data sent from client
do
{
try
{
//read the string sent to the server
theReply = reader.ReadString();
// display the message
displayText.Text += "\r\n" + theReply;
}
// handle the exception if error reading data
catch (Exception)
{
break;
}
} while (theReply != "CLIENT>>> TERMINATE" && connection.Connected);
displayText.Text +=
"\r\nUser terminated connection";
// step 5: close connection
inputText.ReadOnly = true;
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
++counter;
}
} //end try
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}// end method runserver
}// end class server
client
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.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Client
{
public partial class Client : Form
{
private NetworkStream output;
private BinaryWriter writer;
private BinaryReader reader;
private string message = "";
private Thread readThread;
//default constructor
public Client()
{
InitializeComponent();
readThread = new Thread(new ThreadStart(RunClient));
readThread.Start();
}
protected void Client_Closing(
object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
//sends the text user typed to server
protected void inputText_KeyDown(
object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
writer.Write("CLIENT>>> " + inputText.Text);
displayText.Text +=
"\r\nCLIENT>>> " + inputText.Text;
inputText.Clear();
}
}
catch (SocketException ioe)
{
displayText.Text += "\nError writing object";
}
}//end method inputText_KeyDown
//connect to server & display server-generated text
public void RunClient()
{
TcpClient client;
//instantiate TcpClient for sending data to server
try
{
displayText.Text += "Attempting connection\r\n";
//step1: create TcpClient for sending data to server
client = new TcpClient();
client.Connect("localhost", 9000);
//step2: get NetworkStream associated with TcpClient
output = client.GetStream();
//create objects for writing & reading across stream
writer = new BinaryWriter(output);
reader = new BinaryReader(output);
displayText.Text += "\r\nGot I/O streams\r\n";
inputText.ReadOnly = false;
//loop until server terminate
do
{
//step3: processing phase
try
{
//read from server
message = reader.ReadString();
displayText.Text += "\r\n" + message;
}
//handle exception if error in reading server data
catch (Exception)
{
System.Environment.Exit(System.Environment.ExitCode);
}
} while (message != "SERVER>>> TERMINATE");
displayText.Text += "\r\nClosing connection.\r\n";
//step4: close connection
writer.Close();
reader.Close();
output.Close();
client.Close();
Application.Exit();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
}
It is probably your firewall acting up. Try connecting to something like www.google.com on TCP 80 just to see if you can actually connect.
Are you using a newer version of Windows? It's possible that you're only listening on IPv4, but "localhost" is resolving to an IPv6 address and it's not finding it. Try connecting to "127.0.0.1" instead of localhost and see if the result changes.
mk,
I'd tcplistener/tcpclient for simple applications . . .
TheEruditeTroglodyte
If you use that constructor with TCPListener then it will let the underlying service provider pick a network address, which probably won't be 'localhost'. You're probably listening on your LAN/WLAN card instead of localhost.
Take a look at the MSDN page for TCPListener, the sample there shows how to use a different constructor, look at the other constructors for more samples.
Here's one way:
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcpListener = new TcpListener(ipAddress, 9000);

Categories