CodePudding user response:
Like 'chat' implementation, there is no essential difference in text, and sending files,CodePudding user response:
Then how do you put the files into the bytecode send somebody else in the past, and then the somebody else the bytecode parsed into fileCodePudding user response:
Just practice these days, like writing and chat rooms, with a socket can finish, but there are a few attention point1, in the process of transmission byte [] can not be converted to string
2, write file can use FileStream
3, send the file to send the file name and file length in the past, to facilitate receiving
4, in order to distinguish between information and files can be sent in front of the flow of information to add custom rules
Read the Code file
OpenFileDialog OpenFile;
DialogResult m_drTansferFile=new DialogResult ();
OpenFile=new OpenFileDialog ();
OpenFile. Title="Selct a File to Transfer";
M_drTansferFile=OpenFile. ShowDialog ();
If (m_drTansferFile!=DialogResult. OK) {
MessageBox. Show (" Transfer is Cancelled ");
return null;
}
String szFullPath=OpenFile. FileName;
Return szFullPath;
Accept the file Code
byte [] buffer=new byte [128];
M_WorkSocket. The Receive (buffer);
String szText=Encoding. UTF8. Get string (buffer);
SzText=szText. Trim (' \ 0 ');
String [] szMessage=szText. Split (");
Int nLength=int. Parse (szMessage [1]).
String szFileName=szMessage [0];
//define the receiving data cache
Byte [] FileMessage=new byte [nLength];
Int nSum=0;
//for the first time receiving the actual data flag
Int nFlag=m_WorkSocket. The Receive (FileMessage, 0, FileMessage. Length, SocketFlags. None).
//if there is no received fixed data, loop to receive
While (nFlag!=FileMessage. Length) {
NSum +=1;
NFlag +=m_WorkSocket. The Receive (FileMessage nFlag, FileMessage. Length - nFlag SocketFlags. None).
Console. WriteLine (" receiving number: "+ nSum. ToString ());
}
Console. WriteLine (" jump out of the loop ");
String szFullName=string Concat (@ 1 a c # project "E: \ \ ", szFileName);
FileStream fs=new FileStream (szFullName, FileMode. Create);
Fs. Write (FileMessage, 0, FileMessage. Length);
Fs. Flush ();
Console. WriteLine (fs. The Position);
Console. WriteLine (" OK ");