有人可以看看我的套接字代码吗 [英] Could somebody take a look at my socket code
本文介绍了有人可以看看我的套接字代码吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的读者,
我想知道我是否要对此套接字编程所有错误.我的代码可以正常运行,但是我只是怀疑这是正确的.我将按执行顺序发布代码.
服务器:
收听连接
Dear reader,
I am wondering if i am going about this socket programming all wrong. My code is functional but i just have my doubts this is correct. I will be posting code in execution order.
Server:
Listen for connections
mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 1500);
mainSocket.Bind(ipLocal);
mainSocket.Listen(-1);
mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
//请求文件
//首先设置要传输的命令,长度为1-8 uri,ASCII数据
//Request a file
//Set first to transfer command, 1-8 uri length, ASCII data
private void TransferFile(string uri)
{
byte[] tmp = ASCIIEncoding.ASCII.GetBytes(uri);
byte[] data = new byte[tmp.Length + 9];
BitConverter.GetBytes((long)tmp.Length).CopyTo(data, 1);
tmp.CopyTo(data, 9);
data[0] = (byte)cmd.transfer;
SendPacket(clientSocket, data);
}
public void SendPacket(SocketPacket to, byte[] p)
{
if (!IsConnected(to.currentSocket))
{
Disconnect(to);
return;
}
try
{
NetworkStream networkStream = new NetworkStream(to.currentSocket);
networkStream.Write(p, 0, p.Length);
}
catch (Exception)
{
}
}
客户:
//连接到服务器并等待命令
Client:
//connect to server and wait for commands
public void start()
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Loopback, 1500);
clientSocket.Connect(ipEnd);
WaitForData();
}
catch (Exception)
{
}
}
public void WaitForData()
{
try
{
if (pfnCallBack == null)
{
pfnCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket(clientSocket);
result = clientSocket.BeginReceive(theSocPkt.Buffer, 0, 9, SocketFlags.None, pfnCallBack, theSocPkt);
}
catch (Exception)
{}
}
//收到文件传输请求
//File transfer request received
public void OnDataReceived(IAsyncResult asyn)
{
try
{
byte[] tmp = new byte[1024];
string msg = string.Empty;
long length = 0;
long rdby = 0;
int len = 0;
SocketPacket s = (SocketPacket)asyn.AsyncState;
NetworkStream nfs = new NetworkStream(s.currentSocket);
//Read byte 1-8 from BeginReceive buffer to length
length = BitConverter.ToInt64(s.Buffer, 1);
//Read byte 0 with command
switch (s.Buffer[0])
{
case (int)cmd.transfer:
while (rdby < length)
{
len = nfs.Read(tmp, 0, pSize);
if (len == 0) if (!IsConnected(s.currentSocket)) { Dispose(); Start(); };
msg += ASCIIEncoding.ASCII.GetString(tmp, 0, len);
rdby = rdby + len;
}
SendFile(s.currentSocket, msg);
break;
}
}
catch (Exception)
{}
WaitForData();
}
public void SendFile(Socket s, string file)
{
try
{
if (clientSocket != null)
{
FileInfo fi = new FileInfo(file);
int len = 0;
int rdby = 0;
FileStream fin = new FileStream(file, FileMode.Open, FileAccess.Read);
NetworkStream nfs = new NetworkStream(s);
//Send Header, 0= cmd, 1-8 file length
byte[] tmp = new byte[9];
BitConverter.GetBytes(fi.Length).CopyTo(tmp, 1);
tmp[0] = (byte)cmd.transfer;
nfs.Write(tmp, 0, tmp.Length);
//Send File
tmp = new byte[pSize];
while (rdby < fi.Length && nfs.CanWrite)
{
len = fin.Read(tmp, 0, tmp.Length);
nfs.Write(tmp, 0, len);
rdby = rdby + len;
}
fin.Close();
}
}
catch { }
}
private bool IsConnected(Socket socket)
{
try
{
if (socket.Connected)
return !(socket.Poll(100, SelectMode.SelectRead) && socket.Available == 0);
else
return false;
}
catch (SocketException) { return false; }
}
感谢您与我同在,
希望我能从您的回答中学到一些东西.
Thanks for baring with me,
And hopefully i can learn something from your response.
推荐答案
我删除了所有异常代码以缩短我的帖子.
I had removed all the exception code to shorten my post.
这篇关于有人可以看看我的套接字代码吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文