为什么这段代码不起作用?我是 C# 的新手,并从教程中获取了这个。代码中没有错误,但它在调试模式下崩溃。谢谢!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Chat1
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
byte[] buffer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Set up socket
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//Get User IP
textLocalIp.Text = GetLocalIp();
textRemoteIp.Text = GetLocalIp();
}
private string GetLocalIp()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "127.0.0.1";
}
private void buttonConnect_Click(object sender, EventArgs e)
{
// Binding Socket
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
// Connect to Remote IP
epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text));
sck.Bind(epRemote); // This is were it directs me when crashing
//Specific Port
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
byte[] recieveData = new byte[1500];
recieveData = (byte[])aResult.AsyncState;
//Convert Byte To String
ASCIIEncoding aEncoding = new ASCIIEncoding();
string receivedMessage = aEncoding.GetString(recieveData);
//Adding this item into Textbox
listMessage.Items.Add("Partner: " + receivedMessage);
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
// Convert String to Byte
ASCIIEncoding aEncoding = new ASCIIEncoding();
byte[] sendingMessage = new byte[1500];
sendingMessage = aEncoding.GetBytes(textMessage.Text);
// Sending the Enconded message
sck.Send(sendingMessage);
//Add to the Listbox
listMessage.Items.Add("Me: " + textMessage.Text);
textMessage.Text = "";
}
}
}