ash1988

ash1988
- Name: Ashley S
- Favorite Languages: C#
- Website: [not set]
- Location: Australia
- About Me:
4th Electrical Engineering student
-
C# Tutorial - Simple Threaded TCP Server
10/22/2009 - 17:56
disregard my last message, I got it working, you were right about the DataAvailable returning false. I've just placed an infinte true loop around the other loop, not sure if thats the best way to get around it but its working!!
Thanks heaps -
C# Tutorial - Simple Threaded TCP Server
10/21/2009 - 17:17
ok so with that aside, am I right in my understanding that once a "clienstream" has been established between server-client that they can send/receieve using this without any issues with blocking sockets or anything like that?
In your example you have this code to send from server-client
NetworkStream clientStream = tcpClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!");clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();Was I correct in adding a handlecomm method at the client end because how else would the application know how to handle the receival of data?
Im confused in regards to the part where say I go to send a message from client-server, how is it that only the server "handlecomm" and not the client "handlecomm" won't see data in the stream to be read?
Thanks
-
C# Tutorial - Simple Threaded TCP Server
10/21/2009 - 06:26
Hi I've been trying to piece together some code from this tutorial for my application and have come across a few problems.
Can anyone help me out with seeing why I can't send more than one message in either direction with the code I have, and why this would be the case. I get the feeling I've done something seriously wrong!
Thanks for any help.
Server Side
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace TcpTrainServer
{
public partial class Form1 : Form
{
private static TcpListener tcpListener;
private static Thread listenThread;
static NetworkStream clientStream;
static string textFromClient = "";
//private string endl = "\r\n";
public delegate void MessageReceivedHandler(string message);
public event MessageReceivedHandler MessageReceived;
public Form1()
{
InitializeComponent();
initiateListen();
}
private void initiateListen()
{
tcpListener = new TcpListener(IPAddress.Any, 8000);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
}
/// <summary>
/// Listens for client connections
/// </summary>
private static void ListenForClients()
{
tcpListener.Start();
while (true)
{
try
{
// Blocks until a client has connected to the server
TcpClient client = tcpListener.AcceptTcpClient();
// Create a thread to handle communication
// with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
catch (Exception)
{
}
}
}
private void buttonStartListening_Click(object sender, EventArgs e)
{
initiateListen();
}
/// <summary>
/// Handles client connections
/// </summary>
/// <param name="client"></param>
private static void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
//NetworkStream clientStream = tcpClient.GetStream();
clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
do
{
bytesRead = 0;
try
{
// Blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception)
{
// A socket error has occured
break;
}
if (bytesRead == 0)
{
// The client has disconnected from the server
break;
}
// Message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
// Output message
textFromClient = tcpClient.Client.LocalEndPoint + " " + tcpClient.Client.RemoteEndPoint + encoder.GetString(message, 0, bytesRead);
//Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
//Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
//Console.WriteLine(encoder.GetString(message, 0, bytesRead));
} while (clientStream.DataAvailable);
// Release connections
// clientStream.Close();
//tcpClient.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
textBoxMessage.Text = textFromClient;
}
private void buttonClear_Click(object sender, EventArgs e)
{
textFromClient = "";
textBoxMessage.Clear();
}
private void buttonSendToClient_Click(object sender, EventArgs e)
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
Client Side (User App)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace UserApp
{
public partial class Form1 : Form
{
static TcpClient client;
IPEndPoint serverEndPoint;
NetworkStream clientStream;
static String textFromServer;
public Form1()
{
InitializeComponent();
iniTCP();
}
public void iniTCP()
{
client = new TcpClient();
serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);
}
public void connectTCP()
{
client.Connect(serverEndPoint);
clientStream = client.GetStream();
// Create a thread to handle communication
// with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
public void sendMsg()
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Testing TCP/IP connection");
clientStream = client.GetStream();
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
//clientStream.Close();
}
private void button1_Click(object sender, EventArgs e)
{
connectTCP();
}
private void buttonSendMessage_Click(object sender, EventArgs e)
{
sendMsg();
}
/// <summary>
/// Handles client connections
/// </summary>
/// <param name="client"></param>
private static void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
do
{
bytesRead = 0;
try
{
// Blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception)
{
// A socket error has occured
break;
}
if (bytesRead == 0)
{
// The client has disconnected from the server
break;
}
// Message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
// Output message
//textFromServer = tcpClient.Client.LocalEndPoint + " " + tcpClient.Client.RemoteEndPoint + encoder.GetString(message, 0, bytesRead);
textFromServer = tcpClient.Client.LocalEndPoint + " " + tcpClient.Client.RemoteEndPoint + encoder.GetString(message, 0, bytesRead);
} while (clientStream.DataAvailable);
}
private void buttonClose_Click(object sender, EventArgs e)
{
// Release connections
clientStream.Close();
//tcpClient.Close();
}
}
}
Recent Comments