主要实现函数过程如下
//接受函数监听端口,接受数据
public void beginListen()
{
IPHostEntry ihe = new IPHostEntry();
ihe = System.Net.Dns.Resolve(Dns.GetHostName());//获取服务器(本机)ip地址
IPEndPoint iep = new IPEndPoint(ihe.AddressList[0],port);
lisSocket = new Socket(AddressFamily.InterNetwork,System.Net.Sockets.SocketType.Stream,System.Net.Sockets.ProtocolType.Tcp);
byte[] revbyte = new byte[255];
lisSocket.Bind(iep);
while(true)
{
try
{
lisSocket.Listen(100);
Socket newSocket = lisSocket.Accept();
//EndPoint fromEP = lisSocket.RemoteEndPoint; //此句抛出Exception
newSocket.Receive(revbyte);
string allmsg = DateTime.Now.ToString();
allmsg += " from/n" + newSocket.RemoteEndPoint.ToString() + ":/n";
allmsg += Encoding.Default.GetString(revbyte) + "/n";
this.revbox.Text += "/n/n" + allmsg;
}
catch(SocketException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
//发送函数
private void beginsend()
{
IPAddress ipa = IPAddress.Parse(ipaddt.Text);
IPEndPoint iep = new IPEndPoint(ipa,port);
byte[] msg;
if(sndbox.Text.Length >= 255)
{
MessageBox.Show("");
}
//创建发送Socket
try
{
Socket sndSocket = new Socket(AddressFamily.InterNetwork,System.Net.Sockets.SocketType.Stream,System.Net.Sockets.ProtocolType.Tcp);
sndSocket.Connect(iep);
msg = Encoding.Default.GetBytes(sndbox.Text);
sndSocket.Send(msg);
sndSocket.Shutdown(SocketShutdown.Both);
sndSocket.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Form1_Load(object sender, System.EventArgs e)
{
this.MaximizeBox=false;
try
{
newthread = new Thread(new ThreadStart(beginListen));
newthread.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, System.EventArgs e)
{
if(ipaddt.Text == "")
{
MessageBox.Show("请输入IP地址");
}
else
beginsend();
}
private void button2_Click(object sender, System.EventArgs e)
{
this.revbox.Text = ipaddt.SelectionStart.ToString();
sndbox.Text = sndbox.Text.Insert(this.sndbox.SelectionStart,"ahahaha");
}
该博客主要展示了使用C#实现Socket数据收发的函数过程。包含接受函数beginListen监听端口并接受数据,发送函数beginsend用于发送数据,同时在Form1_Load中启动监听线程,还设置了button1和button2的点击事件处理逻辑,过程中对异常进行了捕获处理。
1325

被折叠的 条评论
为什么被折叠?



