2
我的問題是當我的客戶端發送數據時,我的服務器只有它獲得它的第一個發送的消息。服務器未收到的所有以下客戶端消息。 如果我調試客戶端,它不會拋出任何異常,所以我認爲問題在於接受服務器。C# - 服務器套接字不檢索數據
有人可以告訴我如何修復我的客戶端能夠多次發送到服務器的代碼,而無需爲每條消息創建一個新的套接字(在客戶端上)?
服務器:
static Socket connection;
static IPEndPoint endpoint;
const int BUFFER_SIZE = 1024;
static byte[] buffer;
static void Main(string[] args)
{
connection = new Socket(SocketType.Stream, ProtocolType.Tcp);
endpoint = new IPEndPoint(IPAddress.Any, 1337);
connection.Bind(endpoint);
connection.Listen(10);
buffer = new byte[BUFFER_SIZE];
connection.BeginAccept(new AsyncCallback(AsyncAccept),null);
Console.ReadLine();
}
private static void AsyncAccept(IAsyncResult ar)
{
Socket s = connection.EndAccept(ar);
s.BeginReceive(buffer,0,BUFFER_SIZE, SocketFlags.None, new AsyncCallback(AsyncReceive),s);
connection.BeginAccept(new AsyncCallback(AsyncAccept), null);
}
static void AsyncReceive(IAsyncResult ar)
{
Socket s = (Socket)ar.AsyncState;
int received = s.EndReceive(ar); //END
byte[] data = new byte[received];
Array.Copy(buffer, data, received);
string text = Encoding.Default.GetString(data);
Console.WriteLine(text);
}
客戶:
Socket c;
IPEndPoint endpoint;
string text;
public MainWindow()
{
InitializeComponent();
c = new Socket(SocketType.Stream, ProtocolType.Tcp);
endpoint = new IPEndPoint(IPAddress.Loopback, 1337);
c.Connect(endpoint);
}
private void Send()
{
byte[] buffer = Encoding.Default.GetBytes(text);
c.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendAsync), c);
}
private void SendAsync(IAsyncResult ar)
{
Socket s = (Socket)ar.AsyncState;
s.EndSend(ar);
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
Thread t = new Thread(Send);
text = txtMessage.Text;
t.IsBackground = true;
t.Start();
}
片段(考慮修改)。 – deloreyk