我已經嘗試了多種方法來做到這一點,而且似乎無法解決問題。但一定有辦法。C#UDP服務器與客戶端通話
我想要做的(在C#中)是創建一個服務器。我希望服務器監聽IP和端口,當它連接到客戶端時,我希望它讀取客戶端所說的內容併發送回復。對於客戶端,我想連接到服務器併發送數據,並從服務器接收答覆。
我該如何去做這件事?
我已經使用了MSDN上的Microsoft示例和示例。他們有Client> data> Server,但似乎沒有包含服務器回覆。
我知道這可以做,顯然,因爲我們有多人遊戲。
感謝您的幫助。
編輯 - 代碼片段
服務器
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 904);
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newSocket.Bind(endPoint);
Console.WriteLine("Listening for connections...");
//LISTEN FOR CLIENT
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 904);
EndPoint tmpRemote = (EndPoint)sender;
//READ MESSAGE FROM CLIENT
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to server!";
data = Encoding.ASCII.GetBytes(welcome);
//SEND WELCOME REPLY TO CLIENT
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
sock.SendTo(data, tmpRemote);
Console.WriteLine("Reply sent to client");
while (true)
{
if(!newSocket.Connected)
{
Console.WriteLine("Client disconnected.");
break;
}
data = new byte[1024];
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
newSocket.Close();
Console.WriteLine("Server disconnected.");
Console.ReadLine();
}
}
CLIENT
static void Main(string[] args)
{
Console.WriteLine("Message [127.0.0.1:904]: ");
string msg = Console.ReadLine();
byte[] packetData = ASCIIEncoding.ASCII.GetBytes(msg);
string IP = "127.0.0.1";
int port = 904;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
Console.WriteLine("Data sent!");
int recv;
byte[] data = new byte[1024];
EndPoint tmpRemote = (EndPoint)ep;
while(true)
{
//READ MESSAGE FROM SERVER
recv = client.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
client.Close();
Console.WriteLine("Client disconnected.");
Console.ReadLine();
}
我無法讓服務器與客戶端進行對話並讓客戶端讀取/顯示服務器的回覆。
向我們顯示您的代碼。你卡在哪裏?還是你希望我們開始爲你投擲代碼片段? – atlanteh 2014-09-29 23:55:36