0
我是C#中套接字編程的新手。已經瘋狂搜索網絡解決我的問題,但沒有找到任何可以解決它的問題。所以繼承人我的問題:C#套接字編程:服務器不接受客戶端連接
我想寫一個客戶端服務器應用程序。目前,服務器也將在我的本地機器上運行。應用程序從客戶端向服務器傳輸一個字節的數據流。 問題在於服務器沒有檢測到客戶端連接請求,而客戶端能夠連接並傳輸字節流。
這裏是服務器代碼:
String strHostName = Dns.GetHostName();
Console.WriteLine(strHostName);
IPAddress ip = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(ip, port);
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
soc.Bind(ipEnd);
Console.WriteLine("Web Server Running... Press ^C to Stop...");
Thread th = new Thread(new ThreadStart(StartListen));
th.Start();
的StartListen線程如下:
public void StartListen()
{
try
{
while (true)
{
string message;
Byte[] bSend = new Byte[1024];
soc.Listen(100);
if (soc.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\n CLient IP {0}\n", soc.RemoteEndPoint);
Byte[] bReceive = new Byte[1024 * 5000];
int i = soc.Receive(bReceive);
客戶端代碼如下:
hostIPAddress = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(hostIPAddress,port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Console.WriteLine("Connecting to Server...");
clientSocket.Connect(ipEnd);
Console.WriteLine("Sending File...");
clientSocket.Send(clientData);
Console.WriteLine("Disconnecting...");
clientSocket.Close();
Console.WriteLine("File Transferred...");
現在發生的事情是,服務器啓動,當我運行客戶端時,它連接,發送和關閉。但是在服務器控制檯上沒有任何反應,它沒有檢測到任何連接:if(soc.Connected)保持爲假。
我檢查服務器是否通過netstat監聽127.0.0.1:5050,它確實在監聽。不能找出問題。請幫忙。
謝謝,我也只是想出了我自己:) – 2013-03-03 17:53:39
@MuhammadZeeshanArif,太好了。我剛剛添加了代碼來說明這種方法。 – 2013-03-03 17:54:37
親愛的Down-voter,請注意解釋原因。 – 2013-03-05 11:29:08