请问在做socket传输中,怎样才能让接收端连续接收到信息呢?我已经使用了多线程,为什么还是只能接收到到第一次发送的信息?搞这个问题搞了好久了,头都要爆掉了,网上到处都找过了找不到答案,唉,谁能帮个忙呢?急死我了。没有分提供了,真不好意思啊。
接收端代码:
private void receive_Load(object sender, EventArgs e)
{
listin();
}
void listin()
{
IPHostEntry HostIp = Dns.Resolve(Dns.GetHostName());
IPAddress ip = HostIp.AddressList[0];
this.textBox1.Text = ip.ToString();
this.textBox2.Text = "5000";
Thread thred = new Thread(new ThreadStart(receives));
thred.IsBackground = true;
thred.Start();
}
void receives()
{
TcpListener tcplisten = new TcpListener(new IPEndPoint(IPAddress.Any, 5000));
tcplisten.Start();
s = tcplisten.AcceptSocket();
byte[] by = new byte[1024];
int ii;
while (true&&(ii = s.Receive(by)) != 0)
{
string t = System.Text.Encoding.Default.GetString(by, 0, ii);
this.richTextBox1.AppendText(ip.ToString() + " 发来信息:" + t + "\r\n");
}
tcplisten.Stop();
}
发送端代码:
private void button1_Click(object sender, EventArgs e)
{
string d=this.textBox2.Text.ToString();
if (d != "" && Isnumber(d) == true)
{
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(this.textBox1.Text.ToString()),
int.Parse(d));
IP = IPAddress.Parse(textBox1.Text.ToString());
port = int.Parse(d);
Thread thred = new Thread(new ThreadStart(listing));
thred.IsBackground = true;
thred.Start();
}
else
{
MessageBox.Show("请确认端号和IP是否错误!");
}
}
void listing()
{
Control.CheckForIllegalCrossThreadCalls = false;
TcpClient tcpclient = new TcpClient(); //构建TCP命令
tcpclient.Connect(IPAddress.Parse(textBox1.Text.ToString()), port);
if (tcpclient.Connected)
{
string str = this.richTextBox1.Text.ToString();
if (str != "")
{
byte[] by = System.Text.Encoding.ASCII.GetBytes(str);
tcpclient.Client.Send(by, by.Length, SocketFlags.None);
tcpclient.Client.Shutdown(SocketShutdown.Both);
MessageBox.Show("信息发送成功了!");
}
tcpclient.Close();
}