PC Review


Reply
Thread Tools Rate Thread

Bi-directional Socket Listener/Receiver

 
 
Doug
Guest
Posts: n/a
 
      1st Mar 2011
Hey,
I want to create a very quick and dirty bi-directional socket listener
and receiver and have been trying to do it with this code and cannot
get it to work...could someone show me what I'm doing wrong?

private void SendFile(FileInfo file)
{
IPAddress address = IPAddress.Parse(txtIPAddress.Text);

Socket server = server = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
server.Bind(new IPEndPoint(address,
int.Parse(txtPort.Text)));
server.Listen(5);

using (FileStream streamFile = file.OpenRead())
{
byte[] fileBuffer = new byte[4096];
long byteTotal = file.Length;
int byteRead = 0;
int byteSum = 0;

while (byteSum < byteTotal)
{
byteRead = streamFile.Read(fileBuffer, 0,
fileBuffer.Length);
byteSum += byteRead;
}

server.Send(fileBuffer);

byte[] messageBuffer = new byte[1024];

Socket client = null;
string message = string.Empty;


while (true)
{
client = null;
message = string.Empty;

try
{
client = server.Accept();

ASCIIEncoding ascii = new ASCIIEncoding();

char[] messageCharacters = null;
int numberBytes;
int totalBytes = 0;

while ((numberBytes =
client.Receive(messageBuffer, 0, messageBuffer.Length,
SocketFlags.None)) > 0)
{
messageCharacters =
ascii.GetChars(messageBuffer, 0, numberBytes);

for (int index = 0; index <=
(messageCharacters.Length - 1); index++)
{
message += messageCharacters[index];
}

Array.Clear(messageBuffer, 0,
messageBuffer.Length);
totalBytes += numberBytes;
}


client.Close();

string fileName = Path.Combine(@"C:\Doug\Write
\Socket\", Path.GetRandomFileName());

using (StreamWriter writer = new
StreamWriter(fileName))
{
writer.Write(message);
}
}
catch (Exception ex)
{
client.Close();
throw;
}
}
}

}
 
Reply With Quote
 
 
 
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Terminating a socket listener thread in a loop eliss.carmine@gmail.com Microsoft C# .NET 2 3rd Nov 2006 04:47 PM
Socket.BeginSendTo and Socket.BeginSendFrom on a single Socket instancefrom multiple threads Jonas Hei Microsoft Dot NET Framework 9 5th Jul 2005 03:27 AM
Stoping an asyncronous socket listener =?Utf-8?B?bGVl?= Microsoft C# .NET 0 6th Apr 2005 09:25 AM
Asynchronous Socket Listener question =?Utf-8?B?amNhc3Q=?= Microsoft Dot NET Framework 0 19th Aug 2004 10:07 PM
Socket listener with multiple IPEndPoints??? Jon Microsoft C# .NET 3 25th Mar 2004 01:05 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 03:25 AM.