Bi-directional Socket Listener/Receiver

D

Doug

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;
}
}
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top