How to send and receive image using socket programming in c#

my code is successfully sending and receiving images using sockets....but problem is that i want to send messages along images ....ie if client sends all images from a defined location...then client must send a message to tell server....that now its server turn to send image...if i merge messsage along byte data of images then ...on receiving end only image file is created but no previou...means images are not displayed....
code is placed below...

public void ReceiveImage()
{
try
{
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
if (receivedBytesLen == 19)
{
string message = Encoding.ASCII.GetString(clientData, 0, 19);
if (message == "Server_Img_Complete")
{
Thread.Sleep(6000);
SendImage objfrm = new SendImage();
objfrm.getPatientDocuments();
}
}
else
{
receivedPath = System.Configuration.ConfigurationSettings.AppSettings["receivedPath"].ToString();
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
db.openConnection();
string start_from = db.getFieldDescription("SS_EMR_IMAGE_Sync_Time_Log", "top 1 (Date_to) as field_date", "acknowledged = 1 Order By sr desc");
bWrite.Close();
clientSock.Close();
}
ReceiveImage();
}

</code>

Code for Client Application:

class FTClientCode
{
public static void SendFile(string fileName)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string filePath = "";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
if (fileNameByte.Length > 850 * 1024)
{
curMsg = "File size is more than 850kb, please try with small file.";
return;
}
//byte[] clientData = new byte[12 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
byte[] message = Encoding.ASCII.GetBytes("image_ok");
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
message.CopyTo(clientData, fileNameByte.Length + fileData.Length);}
}
clientSock.Connect(ipEnd);
clientSock.Send(clientData);
clientSock.Close();



Awaitng for ur kind response.
Thanks
posted @ 2009-05-26 18:55  EastFuture  阅读(530)  评论(0编辑  收藏  举报