C#网络编程的问题,救命啊,这是怎么回事啊
好吧直接上代码,这是MSDN上套接字使用的服务器端代码,我在窗体上用了个按钮和个Textbox,然后我逐行调试,每次到按下按钮后窗体就现实没有响应了!什么原理啊各位大神!
namespace socket_text
{
public partial class Server : Form
{
static string output = "";
public Server()
{
InitializeComponent();
}
public void createListener()
{
// Create an instance of the TcpListener class.
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
output = "Waiting for a connection...";
}
catch (Exception e)
{
output = "Error: " + e.ToString();
MessageBox.Show(output);
}
while (true)
{
// Always use a Sleep call in a while(true) loop
// to avoid locking up your CPU.
textBox1.Text = "等待中";
Thread.Sleep(10);
// Create a TCP socket.
// If you ran this server on the desktop, you could use
// Socket socket = tcpListener.AcceptSocket()
// for greater flexibility.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
textBox1.Text = "处理中";
// Read the data stream from the client.
byte[] bytes = new byte[256];
NetworkStream stream = tcpClient.GetStream();
stream.Read(bytes, 0, bytes.Length);
SocketHelper helper = new SocketHelper();
helper.processMsg(tcpClient, stream, bytes);
}
}
private void button1_Click(object sender, EventArgs e)
{
createListener();
}
}
public class SocketHelper
{
TcpClient mscClient;
string mstrMessage;
string mstrResponse;
byte[] bytesSent;
public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
{
// Handle the message received and
// send a response back to the client.
mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
mscClient = client;
mstrMessage = mstrMessage.Substring(0, 5);
if (mstrMessage.Equals("Hello"))
{
mstrResponse = "Goodbye";
}
else
{
mstrResponse = "What?";
}
bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
stream.Write(bytesSent, 0, bytesSent.Length);
}
}
} 网络编程
[解决办法]
自己debug下看看,主UI线程都堵在 while(true)那了。界面肯定没响应了
[解决办法]
新开个线程进行网络通讯,要不while(true)是个死循环,界面就卡在哪了
------解决方案--------------------