How do you send a serialized object over net? - c#

i am trying to build a chat! now my goal is to receive input from the user, (which will be fed to a function in a class), save it and send the object to the user over the net.
here is my code so far:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Any, 5000);
server.Start();
Console.WriteLine("Server started");
int a = 0;
while (true)
{
TcpClient connection = server.AcceptTcpClient();
Console.WriteLine("connection accepted");
ThreadPool.QueueUserWorkItem(ProssecClient, connection);
}
}
public static void ProssecClient(object o)
{
TcpClient connection = o as TcpClient;
if (connection == null)
return;
StreamReader sr = new StreamReader(connection.GetStream());
StreamWriter sw = new StreamWriter(connection.GetStream());
string word = "";
savedObject saved = new savedObject();
try
{
while (true)
{
sw.WriteLine(sr.ReadLine());
sw.Flush();
// here the server should read and retrieve,
// everything that it gets to every user that logs in.
}
}
catch
{
Console.WriteLine("client left");
}
}
}
}
i have everything saved in the binaryFormatter, how do i send it to the user to receive?
client side code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
TcpClient connection = new TcpClient("127.0.0.1", 5000);
StreamReader sr = new StreamReader(connection.GetStream());
StreamWriter sw = new StreamWriter(connection.GetStream());
savedObject saved = new savedObject();
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
string word = "";
string allwords = "";
Thread Listen = new Thread(deserialise);
Listen.Start();
while (true)
{
word = Console.ReadLine();
allwords = saved.AllWords(word);
sw.WriteLine(allwords);
sw.Flush();
Console.WriteLine(sr.ReadLine());
//Serialize
//bformatter.Serialize(stream, saved);
//stream.Close();
//sw.WriteLine(saved);
}
}
}
public static void deserialise()
{
//Deserialize
//if (File.Exists("EmployeeInfo.osl"))
//{
// stream = File.Open("EmployeeInfo.osl", FileMode.Open);
// bformatter = new BinaryFormatter();
// saved = (savedObject)bformatter.Deserialize(stream);
// stream.Close();
//}
}
}
[Serializable()]
class savedObject : ISerializable
{
public string allwords;
public string AllWords(string words)
{
allwords += words + " ";
return allwords;
}
public void Words(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("RetrievedWord", allwords);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
allwords = (String)info.GetValue("RetrievedWord", typeof(string));
}
}

Consider WCF.
It handles all communication issues including security, different protocols, etc. from a consistent high-level perspective.
It is pretty much the standard for communication in .Net and encompasses and supersedes the older more low-level technologies.
For a good tutorial of how to build a chat service using WCF see WCF / WPF Chat Application

In the ProcessClient method:
TcpClient client = (TcpClient) connection;
using(StreamWriter streamWriter = new StreamWriter(tcpClient.GetStream()))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(streamWriter, savedObject);
}

You could use a SOAP Arhitecture (use XML Serialization not Bynary serialization)it would be much easyer to implement. Or if you need a peer to peer chat code here .

Related

2 Way messaging system in C# using Sockets

I am trying to make a 2 Way chat messaging system, One that would send a message and the other party gets it and sends back a message and the other party can reply as well. I found a code I have been able to utilize to make mine and it works fine but it's only a one-way message system hence I wanted something that the client can send a message to the server and the server back to the client.
My code looks like this, tho it's a one-way
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Sever
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(4523);
serverSocket.Start();
Console.WriteLine("Started!");
while (true)
{
TcpClient clientSocket = serverSocket.AcceptTcpClient();
handleClient clientx = new handleClient();
clientx.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
Thread xthread = new Thread(msg);
ctThread.Start();
}
private void Chat()
{
byte[] buffer = new byte[100];
while (true)
{
NetworkStream ns = clientSocket.GetStream();
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
}
}
private void msg()
{
byte[] buf2 = new byte[100];
while (true)
{
TcpClient client = new TcpClient("localhost", 4523);
NetworkStream ns = client.GetStream();
string str = Console.ReadLine();
BinaryWriter bw = new BinaryWriter(client.GetStream());
bw.Write(str);
}
}
}
}
Now this is the Client.
class Program
{
static void Main(string[] args)
{
while (true)
{
TcpClient client = new TcpClient("localhost",4523);
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[100];
string str = Console.ReadLine();
BinaryWriter bw = new BinaryWriter(client.GetStream());
bw.Write(str);
}
}
}
What am I Really Missing, Client remains the same?
Ok i finally resolved it , its now a 2 way chat, did it with streamwriter and reader at the same time.. works like a charm
server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Sever
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(4523);
serverSocket.Start();
Console.WriteLine("Started!");
while (true)
{
TcpClient clientSocket = serverSocket.AcceptTcpClient();
handleClient clientx = new handleClient();
clientx.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
ctThread.Start();
}
private void Chat()
{
byte[] buffer = new byte[100];
while (true)
{
NetworkStream ns = clientSocket.GetStream();
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
BinaryWriter bw = new BinaryWriter(clientSocket.GetStream());
string str = Console.ReadLine();
bw.Write(str);
}
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.IO;
namespace Client
{
class Program
{
static void Main(string[] args)
{
while (true)
{
TcpClient client = new TcpClient("localhost",4523);
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[100];
string str = Console.ReadLine();
BinaryWriter bw = new BinaryWriter(client.GetStream());
bw.Write(str);
BinaryReader br = new BinaryReader(client.GetStream());
Console.WriteLine(br.ReadString());
}
}
}
}

Sending and Receiving large amount of data through TCPClient doesnot read all the data

Receiving bytes here in this code(server)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
namespace ByteLengthReading
{
class Program
{
static void Main(string[] args)
{
StartServer();
}
private static TcpListener _listener;
public static void StartServer()
{
IPAddress localIPAddress = IPAddress.Parse("119.43.29.182");
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8001);
_listener = new TcpListener(ipLocal);
_listener.Start();
WaitForClientConnect();
}
private static void WaitForClientConnect()
{
object obj = new object();
_listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
Console.In.ReadLine();
}
private static void OnClientConnect(IAsyncResult asyn)
{
try
{
TcpClient clientSocket = default(TcpClient);
clientSocket = _listener.EndAcceptTcpClient(asyn);
HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
clientReq.StartClient();
}
catch (Exception ex)
{
throw ex;
}
WaitForClientConnect();
}
public class HandleClientRequest
{
TcpClient _clientSocket;
NetworkStream _networkStream = null;
public HandleClientRequest(TcpClient clientConnected)
{
this._clientSocket = clientConnected;
}
public void StartClient()
{
_networkStream = _clientSocket.GetStream();
WaitForRequest();
}
public void WaitForRequest()
{
byte[] buffer = new byte[_clientSocket.ReceiveBufferSize];
_networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
}
private void ReadCallback(IAsyncResult result)
{
NetworkStream networkStream = _clientSocket.GetStream();
byte[] buffer = new byte[16384];
int read = -1;
int totRead = 0;
using (FileStream fileStream = new FileStream(#"C:\Foo" + Guid.NewGuid().ToString("N") + ".txt", FileMode.Create))
{
while ((read = networkStream.Read(buffer, 0, buffer.Length)) > 0)
{
totRead += read;
fileStream.Write(buffer, 0, read);
Console.WriteLine("Total Read" + totRead);
//fileStream.Write(buffer, 0, totRead);
//fileStream.Close();
}
fileStream.Close();
}
}
}
}
Sending bytes (Client), Sending bytes of length 4047810. But the abover server code is recieving only 4039618 bytes. Please help someone. Don't know y? At the time of reading last set of data it is coming out of the while loop. Please test this code and tell me where the problem lies.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
using System.Threading;
namespace ByteLengthSending
{
class Program
{
static void Main(string[] args)
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IPAddress.Parse("119.43.29.182"), 8001);
//IPAddress ipAd = IPAddress.Parse("119.43.29.182");
//TcpClient client = new TcpClient(ipAd.ToString(), 8001);
//NetworkStream stream = client.GetStream();
int totread = 0;
byte[] longBuffer = new byte[3824726];
byte[] buffer = new byte[4096];
using (var fileStream = File.OpenRead("C:/Foo.txt"))
{
while (true)
{
int read = fileStream.Read(buffer, 0, buffer.Length);
totread += read;
if (read <= 0)
{
break;
}
for (int sendBytes = 0; sendBytes < read; sendBytes += client.Send(buffer, sendBytes, read - sendBytes, SocketFlags.None))
{
}
}
}
client.Close();
Console.WriteLine("Total Read" + totread);
Console.In.ReadLine();
}
}
}
Here is a sample which uses my library Griffin.Framework to transmit a file (Apache license).
All you need to do is to install the nuget package "griffin.framework" and then create a console application and replace Program class with the following:
class Program
{
static void Main(string[] args)
{
var server = new ChannelTcpListener();
server.MessageReceived = OnServerReceivedMessage;
server.Start(IPAddress.Any, 0);
var client = new ChannelTcpClient<object>(new MicroMessageEncoder(new DataContractMessageSerializer()),
new MicroMessageDecoder(new DataContractMessageSerializer()));
client.ConnectAsync(IPAddress.Loopback, server.LocalPort).Wait();
client.SendAsync(new FileStream("TextSample.txt", FileMode.Open)).Wait();
Console.ReadLine();
}
private static void OnServerReceivedMessage(ITcpChannel channel, object message)
{
var file = (Stream) message;
var reader = new StreamReader(file);
var fileContents = reader.ReadToEnd();
Console.WriteLine(fileContents);
}
}
The library can send/receive any type of stream of any size (as long as the size is known). The client will automatically create a MemoryStream or FileStream depending on the stream size.

Trying to stream 2 way audio over TCP?

I'm trying to make a video conferencing application (written in c#) that would allow 2 users to video conference using TCP. In addition, users can text chat separately. Right now, I have a working video stream, yet don't have the audio working yet. I'm unsure of how to access the microphone, stream it using TCP, and then play it on the other user's speakers as I'm relatively new to c# and brand new to using media.
If anyone could point me towards sample code, help me know how to access the mic, or anything else you think would help me, that'd be great.
I'm attaching my code as is for reference.
WEBCAM.cs
using System;
using System.IO;
using System.Linq;
using System.Text;
using WebCam_Capture;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using System.Net;
using System.Net.Sockets;
using System.Windows;
namespace DuckTalk
{
class WebCam
{
const int TEXT_VIDEO_NUM = 45674;
private System.Windows.Controls.TextBox _hostIpAddressBox;
private WebCamCapture webcam;
private int FrameNumber = 30;
public void InitializeWebCam(ref System.Windows.Controls.TextBox hostIpAddressBox)
{
webcam = new WebCamCapture();
webcam.FrameNumber = ((ulong)(0ul));
webcam.TimeToCapture_milliseconds = FrameNumber;
webcam.ImageCaptured += new WebCamCapture.WebCamEventHandler(webcam_ImageCaptured);
_hostIpAddressBox = hostIpAddressBox;
}
void webcam_ImageCaptured(object source, WebcamEventArgs e)
{
TcpClient connection = null;
NetworkStream stream = null;
byte[] imgBytes;
try
{
//Set up IPAddress
IPAddress ipAddress = IPAddress.Parse(_hostIpAddressBox.Text);
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, TEXT_VIDEO_NUM);
//Connect to TCP
connection = new TcpClient();
connection.Connect(ipLocalEndPoint);
// Get a client stream for reading and writing.
stream = connection.GetStream();
//Send image as bytes
imgBytes = ImageByteConverter.ImageToBytes((System.Drawing.Bitmap)e.WebCamImage);
stream.Write(imgBytes, 0, imgBytes.Length);
}
catch (Exception error)
{
MessageBox.Show("ERROR: " + error.Message);
}
finally
{
// Close everything.
if (connection != null)
connection.Close();
if (stream != null)
stream.Close();
}
}
public void Start()
{
webcam.TimeToCapture_milliseconds = FrameNumber;
webcam.Start(0);
}
public void Stop()
{
webcam.Stop();
}
}
}
ImageByteConverter.cs
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
namespace DuckTalk
{
class ImageByteConverter
{
public static byte[] ImageToBytes(System.Drawing.Bitmap bitmap)
{
byte[] byteArray;
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
public static BitmapImage BytesToImage(byte[] imgBytes)
{
var image = new BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(imgBytes);
image.EndInit();
return image;
}
}
}
Window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
namespace DuckTalk
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class MainWindow : Window
{
const int TEXT_PORT_NUM = 45673;
const int TEXT_VIDEO_NUM = 45674;
WebCam webcam;
public MainWindow()
{
InitializeComponent();
}
private void mainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
webcam = new WebCam();
webcam.InitializeWebCam(ref xaml_hostTextBox);
var _backgroundIMWorker = new BackgroundWorker();
var _backgroundVidWorker = new BackgroundWorker();
_backgroundIMWorker.WorkerReportsProgress = true;
_backgroundVidWorker.WorkerReportsProgress = true;
// Set up the Background Worker Events
_backgroundIMWorker.DoWork += new DoWorkEventHandler(keepListeningForInstantMessages);
_backgroundVidWorker.DoWork += new DoWorkEventHandler(keepListeningForVideoMessages);
// Run the Background Workers
_backgroundIMWorker.RunWorkerAsync();
_backgroundVidWorker.RunWorkerAsync();
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
//
// The next 2 functions take care of the instant messaging part of the program
//
//
//
///////////////////////////////////////////////////////////////////////////////////////////////
private void keepListeningForInstantMessages(object sender, DoWorkEventArgs e)
{
Action<string> displayIncomingMessage = (incomingMsg) =>
{
xaml_incomingTextBox.Text += "\n\nINCOMING MESSAGE: " + incomingMsg;
xaml_incomingTextScroll.ScrollToBottom();
};
Socket connection;
Byte[] data;
String msg;
// create the socket
Socket listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// bind the listening socket to the port
IPEndPoint ep = new IPEndPoint(IPAddress.Any, TEXT_PORT_NUM);
listenSocket.Bind(ep);
while (true)
{
msg = "";
data = new Byte[3000];
// start listening
listenSocket.Listen(1);
//Received a connection
connection = listenSocket.Accept();
//Get Data
connection.Receive(data);
//Get the message in string format
msg = System.Text.Encoding.Default.GetString(data);
msg = msg.Substring(0,msg.IndexOf((char)0));
//Send message to the UI
xaml_incomingTextBox.Dispatcher.BeginInvoke(displayIncomingMessage, msg);
connection.Close();
}
}//end of keepListeningForInstantMessages
void SendInstantMsg(object sender, RoutedEventArgs e)
{
TcpClient connection = null;
NetworkStream stream = null;
byte[] data;
xaml_incomingTextBox.Text += "\n\nOUTGOING MESSAGE: " + xaml_outgoingTextBox.Text;
try
{
//Set up IPAddress
IPAddress ipAddress = IPAddress.Parse(xaml_hostTextBox.Text);
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, TEXT_PORT_NUM);
//Connect to TCP
connection = new TcpClient();
connection.Connect(ipLocalEndPoint);
//Convert text to bytes
data = System.Text.Encoding.ASCII.GetBytes(xaml_outgoingTextBox.Text);
// Get a client stream for reading and writing.
stream = connection.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Count());
xaml_outgoingTextBox.Text = "";
}
catch (Exception error)
{
MessageBox.Show("ERROR: " + error.Message);
}
finally
{
// Close everything.
if (connection != null)
connection.Close();
if (stream != null)
stream.Close();
}
}//end of SendInstantMsg
///////////////////////////////////////////////////////////////////////////////////////////////
//
//
// The next 2 functions take care of the video part of the program
//
//
//
///////////////////////////////////////////////////////////////////////////////////////////////
private void keepListeningForVideoMessages(object sender, DoWorkEventArgs e)
{
Action<Byte[]> displayIncomingVideo = (incomingImgBytes) =>
{
xaml_incomingVideo.Source = ImageByteConverter.BytesToImage(incomingImgBytes);
};
Socket connection;
Byte[] incomingBytes;
Byte[] data;
int offset;
int numOfBytesRecieved;
// create the socket
Socket listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// bind the listening socket to the port
IPEndPoint ep = new IPEndPoint(IPAddress.Any, TEXT_VIDEO_NUM);
listenSocket.Bind(ep);
while (true)
{
offset = 0;
numOfBytesRecieved = -1;
incomingBytes = new Byte[300000];
// start listening
listenSocket.Listen(1);
//Received a connection
connection = listenSocket.Accept();
//Get all the data from the connection stream
while (numOfBytesRecieved != 0)
{
numOfBytesRecieved = connection.Receive(incomingBytes, offset, 10000, SocketFlags.None);
offset += numOfBytesRecieved;
}
data = new Byte[offset];
Array.Copy(incomingBytes, data, offset);
//Send image to the UI
xaml_incomingTextBox.Dispatcher.BeginInvoke(displayIncomingVideo, data);
connection.Close();
}
}//end of keepListeningForVideoMessages
private void SendVideoMsg(object sender, RoutedEventArgs e)
{
xaml_incomingVideo.Visibility = Visibility.Visible;
xaml_StopVideoButton.Visibility = Visibility.Visible;
xaml_SendTextButton.Visibility = Visibility.Hidden;
webcam.Start();
}
private void StopVideoMsg(object sender, RoutedEventArgs e)
{
xaml_incomingVideo.Visibility = Visibility.Hidden;
xaml_StopVideoButton.Visibility = Visibility.Hidden;
xaml_SendTextButton.Visibility = Visibility.Visible;
webcam.Stop();
}
}//end of Class
}//end of NameSpace
You should try downloading NAudio, it is an open source audio library. It comes with a demo on how to stream audio using UDP from one pc to another; it is in the NAudioDemo app called "Network Chat".
http://naudio.codeplex.com/
TCP which you are currently using is not really recommended for audio. Use UDP instead
http://www.onsip.com/about-voip/sip/udp-versus-tcp-for-voip
Alternatively, if you do not want to reinvent the wheel ( I am not sure what is your ultimate goal with your project ), you can try downloading our iConf.NET video conferencing SDK that does most of the leg work for you ( but is not free )
http://avspeed.com/

Client Server Winforms C#

I am trying to build a basic server client application in winforms. However the server does nothing. Just sort of opens up and hangs if i may say so. What am i doing wrong. I made the application as follows:
The Server Winform
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.Threading;
using System.IO;
namespace ServerWinForms
{
public partial class Form1 : Form
{
public delegate void AddText(TcpClient tcp, RichTextBox rtb);
public AddText myDelegate;
Thread myThread;
public Form1()
{
InitializeComponent();
myDelegate = new AddText(ClientSession);
}
void begin(Object obj)
{
var loaclAddress = IPAddress.Parse("127.0.0.1");
var tcpListener = new TcpListener(loaclAddress, 81);
tcpListener.Start();
while (true)
{
var tcpClient = tcpListener.AcceptTcpClient();
Form1 myForm1 = (Form1)obj;
myForm1.Invoke(myForm1.myDelegate);
//rtb.AppendText("Waiting for connection ");
// Console.WriteLine("Waiting for a connection");
//rtb.AppendText("Client Accepted ");
//Console.WriteLine("Client Accepted");
/*Thread thread = new Thread(() => ClientSession(tcpClient))
{
IsBackground = true
};
thread.Start();
//Console.WriteLine("Client Session thread started");
*/
}
}
private static bool tryRead(Stream stream, byte[] buffer, int offset, int count)
{
int bytesRead;
while (count > 0 && (bytesRead = stream.Read(buffer, offset, count)) > 0)
{
offset += bytesRead;
count -= bytesRead;
}
return count == 0;
}
public static void ClientSession(TcpClient tcpClient, RichTextBox rtb)
{
const int totalByteBuffer = 4096;
byte[] buffer = new byte[256];
// UC ucObj = new UC();
using (var networkStream = tcpClient.GetStream())
using (var bufferedStream = new BufferedStream(networkStream, totalByteBuffer))
while (true)
{
if (!tryRead(bufferedStream, buffer, 0, 1))
{
break;
}
byte messageLen = buffer[0];
if (!tryRead(bufferedStream, buffer, 1, messageLen))
{
break;
}
var message = Encoding.ASCII.GetString(buffer, 1, messageLen);
//Console.WriteLine(/*"Message Recieved: {0}", */ message);
RichTextBox rcb = new RichTextBox();
rtb.AppendText(message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
myThread = new Thread(begin);
myThread.Start(this);
//begin();
}
}
}
The Client Winform (though i believe everything is in order here but still... )
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;
namespace ClientWinForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private static byte[] msg2ByteArray(string message, Encoding enc)
{
var byteCount = enc.GetByteCount(message);
if (byteCount > byte.MaxValue)
{
throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
}
var byteArray = new byte[byteCount + 1];
byteArray[0] = (byte)byteCount;
enc.GetBytes(message, 0, message.Length, byteArray, 1);
return byteArray;
}
void sendMsg()
{
String message;
using (var tcpClient = new TcpClient())
{
tcpClient.Connect("127.0.0.1", 81);
using (var networkStream = tcpClient.GetStream())
using (var bufferedStream = new BufferedStream(networkStream))
{
//while (true)
//{
byte[] buffer = new byte[256];
//Console.WriteLine("Write Message");
message = richTextBox.Text;
var byteArray = msg2ByteArray(message, Encoding.ASCII);
bufferedStream.Write(byteArray, 0, byteArray.Length);
bufferedStream.Flush();
//}
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
sendMsg();
}
}
}
kewal, your code looks good and your program also. i also liked that you share all the code, it is most frustrating when i need to ask almost every other asked to do that.
now to the problem. you use tcpListener.Start(); in your server.
as we can read here:
"If a connection request is received, the Start method will queue
the request and continue listening for additional requests until you
call the Stop method"
i believe what you wanted is to use AcceptSocket() method - read
here
i can suggest: use different port. low number ports are taken
already and might not work. i think 81 if for http's, though i'm not
sure
EDIT
3. for the client use this MSDN example to see if the basic
example works for you

IOException The process cannot access the file because it is being used by another process when using XDocument

I keep getting an IOException that it cannot access the file because it's being used by another process. What i'm trying to do is that everytime the file i'm looking at is changed.. it's sending it as an array through TCP/IP. i couldn't find any way of closing the XDocument and just don't know how to fix this error... i google'd and still couldn't find anything. any help would be grateful
edit: i found other solutions with filereader and other things.. but it seems different when using xdocument
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//filesystemwatcher
using System.IO;
//tcpip server
using System.Net;
using System.Net.Sockets;
//XML
using System.Xml;
using System.Xml.Linq;
namespace ChampSelect_FileWatcher
{
class Program
{
//TCP IP variables
public static Int32 port;
public static IPAddress localAddr;
public static TcpListener server;
public static TcpClient client;
public static NetworkStream stream;
public static XDocument doc;
public static void Main(string[] args)
{
//LOAD XML FILE
doc = XDocument.Load("C:/Trio Scripts/example.xml");
//OBSERVE FILE
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = #"C:\Trio Scripts";
watcher.Filter = "example.xml";
//watch for changes in LastWrite
watcher.NotifyFilter = NotifyFilters.LastWrite;
//event handler
watcher.Changed += new FileSystemEventHandler(OnChanged);
//Begin watching
watcher.EnableRaisingEvents = true;
//TCP IP SERVER
try
{
Console.WriteLine("Waiting for 99150 to run...\n");
//config TCP stuff
port = 9905;
localAddr = IPAddress.Parse("10.0.0.66");
server = new TcpListener(localAddr, port);
server.Start();
client = server.AcceptTcpClient();
stream = client.GetStream();
Console.WriteLine("Connection to Viz successful!");
Console.WriteLine("***LISTENING FOR CHANGES TO: " + watcher.Filter + "***\n");
}
catch (SocketException z)
{
Console.WriteLine("SocketException: {0}", z);
}
//prevent console from closing
Console.ReadKey();
Console.ReadKey();
Console.ReadKey();
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
//reload xml file
//doc = XDocument.Load("C:/Trio Scripts/example.xml");
//doc.Root.ReplaceWith(XElement.Load("C:/Trio Scripts/example.xml"));
XDocument doc;
using (var reader = XmlReader.Create("C:/Trio Scripts/example.xml"))
{
doc = XDocument.Load(reader);
}
// Nodes in XML
string[] bans = doc.Descendants("ban").OrderBy(element => Int32.Parse(element.Attribute("order").Value)).Select(element => element.Value).ToArray();
// String to send the message on
String sendMsg = "";
// Proceed with reading XML
for (int i = 0; i < bans.Length; i++)
sendMsg += bans[i] + " ";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(sendMsg);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Change detected, sending changes to Viz");
sendMsg = "";
}
}//end class
}//end namespace
The problem is that you get multiple change events whenever a file is changed.
You should wait a little time before reading the changed file.
Also you should use the e.FullPath and check the
e.ChangeType == WatcherChangeTypes.Changed
If you fail to open the file you should try again later.
You can still use XDocument and an XmlReader:
XDocument doc;
using (var reader = XmlReader.Create("C:/Trio Scripts/example.xml"))
{
doc = XDocument.Load(reader);
}
When the using block completes for the reader, then the file handle should be closed.
Update:
Maybe the behavior of XmlReader.Create(string) doesn't open the file in the most minimal fashion. In case that's what's causing the exception, try this more explicit code specifying file permissions:
XDocument doc;
using (var stream = File.Open("C:/Trio Scripts/example.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = XmlReader.Create(stream))
{
doc = XDocument.Load(reader);
}

Categories

Resources