请大家帮忙看看。
很多问题.比如关闭连接等。很多ERROR。 Socket m_ListenSocket = null;
Socket m_SendSocket = null;
Socket socket = null;
Thread thread = null;
delegate void UIHandler(string msg);
public frmComm()
{
InitializeComponent();
}
private void frmComm_Load(object sender, EventArgs e)
{
btnClose.Enabled = false;
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily != AddressFamily.InterNetworkV6)
{
txtLocalIP.Text = ip.ToString();
break;
}
}
}
//display 略。
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Text File|*.txt";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFile.Text = openFileDialog.FileName;
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (txtFile.Text == "")
{
MessageBox.Show("Please click \"Browse\" to select a file ...", "Information");
return;
}
if (m_SendSocket == null || !m_SendSocket.Connected)
{
MessageBox.Show("Please Connect First ...", "Information");
return;
}
string file = txtFile.Text;
if (File.Exists(file))
{
string msg = File.ReadAllText(file, Encoding.Default); byte[] buf = StringToByteArray(msg);
if (buf != null)
{
this.Invoke(new UIHandler(DisplayMe), msg);
SendMessage(buf);
}
}
else
{
MessageBox.Show("File not exists ...", "Information");
}
}
private byte[] StringToByteArray(string msg)
{
byte[] buf_msg = System.Text.UTF8Encoding.UTF8.GetBytes(msg);
if (buf_msg.Length > 0xffff)
{
MessageBox.Show("Message Length : " + buf_msg.Length, "Information");
return null;
}
byte[] buf = new byte[buf_msg.Length + 2];
int index = 0;
Array.Copy(BitConverter.GetBytes(buf_msg.Length), 0, buf, index, 2);
index += 2;
Array.Copy(buf_msg, 0, buf, index, buf_msg.Length);
index += buf_msg.Length; return buf;
}
private string ByteArrayToString(byte[] buf)
{
string msg = System.Text.UTF8Encoding.UTF8.GetString(buf);
return msg;
}
private void SendMessage(byte[] buf)
{
if (m_SendSocket.Connected)
{
try
{
m_SendSocket.Send(buf);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
else
{
MessageBox.Show("Please connect first ...", "Information");
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (m_SendSocket != null && m_SendSocket.Connected)
{
MessageBox.Show("Already Connected!");
return;
}
try
{
m_SendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); }
catch (SocketException exp)
{
MessageBox.Show(exp.Message);
return;
}
IPEndPoint ipep = GetIPEndPoint();
try
{
m_SendSocket.Connect(ipep);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
return;
}
lblStatus.Text = "Connected!";
}
private void ReceiveMsg()
{
int receiveIndex = 0;
int processIndex = 0;
byte[] buf = new byte[4096];
int len = 0; try
{
lock(m_ListenSocket)
socket = m_ListenSocket.Accept();
}
catch
{
return;
}
if (socket == null)
{
return;
}
while (socket != null && socket.Connected)
{
try
{ len = socket.Receive(buf, receiveIndex, buf.Length - receiveIndex, SocketFlags.None);
if (len == 0)
{
MessageBox.Show("Disconnected by remote client.");
DisconnectSocket();
return;
}
receiveIndex += len;
if (receiveIndex - processIndex > 2)
{
len = BitConverter.ToUInt16(buf, processIndex); while (receiveIndex - processIndex >= len + 2)
{
byte[] buf_msg = new byte[len];
Array.Copy(buf, processIndex + 2, buf_msg, 0, len);
string msg = ByteArrayToString(buf_msg);
//rtbMsg.AppendText(msg);
this.Invoke(new UIHandler(Display), msg); processIndex += buf_msg.Length + 2;
if (!(receiveIndex - processIndex > 2))
{
break;
}
len = BitConverter.ToUInt16(buf, processIndex);
}
Array.Copy(buf, processIndex, buf, 0, receiveIndex - processIndex);
receiveIndex -= processIndex;
processIndex = 0;
}
}
catch (SocketException ex)
{
MessageBox.Show("Disconnected");
DisconnectSocket();
this.Invoke(new Action<object>(EnableListenButton), new object[] { null });
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{ } }
}
private void DisconnectSocket()
{
if (socket != null && socket.Connected)
{
socket.Disconnect(false);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
private void EnableListenButton(object obj)
{
btnListen.Enabled = true;
}
private IPEndPoint GetIPEndPoint()
{
IPAddress ipAdd = null;
bool success = IPAddress.TryParse(txtConnectIP.Text, out ipAdd);
if (!success)
{
ipAdd = null;
MessageBox.Show("Invalid IP Address ...", "Information");
return null;
}
int port;
success = int.TryParse(txtConnectPort.Text, out port);
if (!success)
{
port = -1;
MessageBox.Show("Invalid Port number ...", "Information");
return null;
}
try
{
return new IPEndPoint(ipAdd, port);
}
catch (ArgumentOutOfRangeException exp)
{
MessageBox.Show(exp.Message);
return null;
}
}
private void btnListen_Click(object sender, EventArgs e)
{
int port;
bool success = int.TryParse(txtListenPort.Text, out port);
if (!success)
{
MessageBox.Show("Invalid Listening Post number ...", "Information");
return;
}
try
{
m_ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_ListenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
m_ListenSocket.Listen(10);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
thread = new Thread(new ThreadStart(ReceiveMsg));
thread.Start();
lblStatus.Text = "Start Listening";
btnListen.Enabled = false;
btnClose.Enabled = true;
}
private void btnClear_Click(object sender, EventArgs e)
{
rtbMsg.Clear();
}
private void btnClose_Click(object sender, EventArgs e)
{
DisconnectSocket();
m_ListenSocket.Close();
//thread.Abort();
btnClose.Enabled = false;
btnListen.Enabled = true;
}
private void frmComm_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
很多问题.比如关闭连接等。很多ERROR。 Socket m_ListenSocket = null;
Socket m_SendSocket = null;
Socket socket = null;
Thread thread = null;
delegate void UIHandler(string msg);
public frmComm()
{
InitializeComponent();
}
private void frmComm_Load(object sender, EventArgs e)
{
btnClose.Enabled = false;
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily != AddressFamily.InterNetworkV6)
{
txtLocalIP.Text = ip.ToString();
break;
}
}
}
//display 略。
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Text File|*.txt";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFile.Text = openFileDialog.FileName;
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (txtFile.Text == "")
{
MessageBox.Show("Please click \"Browse\" to select a file ...", "Information");
return;
}
if (m_SendSocket == null || !m_SendSocket.Connected)
{
MessageBox.Show("Please Connect First ...", "Information");
return;
}
string file = txtFile.Text;
if (File.Exists(file))
{
string msg = File.ReadAllText(file, Encoding.Default); byte[] buf = StringToByteArray(msg);
if (buf != null)
{
this.Invoke(new UIHandler(DisplayMe), msg);
SendMessage(buf);
}
}
else
{
MessageBox.Show("File not exists ...", "Information");
}
}
private byte[] StringToByteArray(string msg)
{
byte[] buf_msg = System.Text.UTF8Encoding.UTF8.GetBytes(msg);
if (buf_msg.Length > 0xffff)
{
MessageBox.Show("Message Length : " + buf_msg.Length, "Information");
return null;
}
byte[] buf = new byte[buf_msg.Length + 2];
int index = 0;
Array.Copy(BitConverter.GetBytes(buf_msg.Length), 0, buf, index, 2);
index += 2;
Array.Copy(buf_msg, 0, buf, index, buf_msg.Length);
index += buf_msg.Length; return buf;
}
private string ByteArrayToString(byte[] buf)
{
string msg = System.Text.UTF8Encoding.UTF8.GetString(buf);
return msg;
}
private void SendMessage(byte[] buf)
{
if (m_SendSocket.Connected)
{
try
{
m_SendSocket.Send(buf);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
else
{
MessageBox.Show("Please connect first ...", "Information");
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (m_SendSocket != null && m_SendSocket.Connected)
{
MessageBox.Show("Already Connected!");
return;
}
try
{
m_SendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); }
catch (SocketException exp)
{
MessageBox.Show(exp.Message);
return;
}
IPEndPoint ipep = GetIPEndPoint();
try
{
m_SendSocket.Connect(ipep);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
return;
}
lblStatus.Text = "Connected!";
}
private void ReceiveMsg()
{
int receiveIndex = 0;
int processIndex = 0;
byte[] buf = new byte[4096];
int len = 0; try
{
lock(m_ListenSocket)
socket = m_ListenSocket.Accept();
}
catch
{
return;
}
if (socket == null)
{
return;
}
while (socket != null && socket.Connected)
{
try
{ len = socket.Receive(buf, receiveIndex, buf.Length - receiveIndex, SocketFlags.None);
if (len == 0)
{
MessageBox.Show("Disconnected by remote client.");
DisconnectSocket();
return;
}
receiveIndex += len;
if (receiveIndex - processIndex > 2)
{
len = BitConverter.ToUInt16(buf, processIndex); while (receiveIndex - processIndex >= len + 2)
{
byte[] buf_msg = new byte[len];
Array.Copy(buf, processIndex + 2, buf_msg, 0, len);
string msg = ByteArrayToString(buf_msg);
//rtbMsg.AppendText(msg);
this.Invoke(new UIHandler(Display), msg); processIndex += buf_msg.Length + 2;
if (!(receiveIndex - processIndex > 2))
{
break;
}
len = BitConverter.ToUInt16(buf, processIndex);
}
Array.Copy(buf, processIndex, buf, 0, receiveIndex - processIndex);
receiveIndex -= processIndex;
processIndex = 0;
}
}
catch (SocketException ex)
{
MessageBox.Show("Disconnected");
DisconnectSocket();
this.Invoke(new Action<object>(EnableListenButton), new object[] { null });
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{ } }
}
private void DisconnectSocket()
{
if (socket != null && socket.Connected)
{
socket.Disconnect(false);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
private void EnableListenButton(object obj)
{
btnListen.Enabled = true;
}
private IPEndPoint GetIPEndPoint()
{
IPAddress ipAdd = null;
bool success = IPAddress.TryParse(txtConnectIP.Text, out ipAdd);
if (!success)
{
ipAdd = null;
MessageBox.Show("Invalid IP Address ...", "Information");
return null;
}
int port;
success = int.TryParse(txtConnectPort.Text, out port);
if (!success)
{
port = -1;
MessageBox.Show("Invalid Port number ...", "Information");
return null;
}
try
{
return new IPEndPoint(ipAdd, port);
}
catch (ArgumentOutOfRangeException exp)
{
MessageBox.Show(exp.Message);
return null;
}
}
private void btnListen_Click(object sender, EventArgs e)
{
int port;
bool success = int.TryParse(txtListenPort.Text, out port);
if (!success)
{
MessageBox.Show("Invalid Listening Post number ...", "Information");
return;
}
try
{
m_ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_ListenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
m_ListenSocket.Listen(10);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
thread = new Thread(new ThreadStart(ReceiveMsg));
thread.Start();
lblStatus.Text = "Start Listening";
btnListen.Enabled = false;
btnClose.Enabled = true;
}
private void btnClear_Click(object sender, EventArgs e)
{
rtbMsg.Clear();
}
private void btnClose_Click(object sender, EventArgs e)
{
DisconnectSocket();
m_ListenSocket.Close();
//thread.Abort();
btnClose.Enabled = false;
btnListen.Enabled = true;
}
private void frmComm_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货