日期:2014-05-17  浏览次数:20810 次

c#网络通信问题 服务器只能接收一次信息
服务器代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace receive
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Thread thread = new Thread(new ThreadStart(SocketListen));
            thread.Start();
            IPAddress ipAddress = IPAddress.Any; 
        }
        protected delegate void UpdateDisplayDelegate(string text);
        public void SocketListen()
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, 9999));
            listener.Listen(10);
            Socket s = listener.Accept();
            while (true)
            {
                Stream netStream = new NetworkStream(s);
                StreamReader reader = new StreamReader(netStream);
                string result = reader.ReadToEnd();
                Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });
            }
        }
        public void UpdateDisplay(string text)
        {
            textBox1.Text += text; 
        }
    }
}
客户端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace send
{
    public partial class