我在C#(WindowsForm)中開發了一個客戶端/服務器應用程序來連接網絡上的兩臺計算機。當另一個套接字不再可用時,C#套接字保持連接狀態
下面是它如何工作的:
-The客戶端等待服務器開放(是的,我倒角色)
- 當服務器開啓了,客戶端到達連接
這裏的問題:如果我在連接期間關閉服務器,客戶端仍然連接。
這是一個問題,因爲當我關閉服務器(和客戶端保持連接),如果我重新打開客戶端無法連接了,因爲它仍然連接以前的套接字服務器(服務器我關)
我想在客戶端(和服務器太)能夠DETECT當其他插座斷開連接,當發生這種情況,我想在客戶端重新偵聽傳入的連接(因爲它是第一次)。
這裏的客戶端的源代碼:()
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
namespace _Client
{
public partial class Form1 : Form
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread connection = new Thread(new ThreadStart(DoWork));
connection.Start();
}
private void DoWork()
{
ListenForIncomingConnection();
try
{
byte[] clientRequest = new byte[1024];
while (true)
{
int sizeOfRequest = client.Receive(clientRequest);
byte[] Request = new byte[sizeOfRequest];
Array.Copy(clientRequest, Request, sizeOfRequest);
string _stringRequest = Encoding.ASCII.GetString(Request);
// if the server sends a disconnecting message...
if(_stringRequest == "disconnecting")
{
client.Close();
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.ToString());
DoWork();
}
}
private void ListenForIncomingConnection()
{
try
{
client.Connect("x.xxx.xxx.xxx", 27018);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
ListenForIncomingConnection();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
client.Close();
}
}
}
當服務器斷開連接時,客戶端關閉與client.Close的連接。之後,客戶端嘗試重新連接到服務器,並且出現此錯誤:無法訪問處置的對象 這是因爲在客戶端嘗試重新連接之前,我使用client.Close()關閉了連接。
如何解決?
我不使用c#,但通過它的外觀你的「if(client.Available> 0)」是一個毫無意義的檢查。 「client.Receive(clientRequest)」應該是一個阻塞調用。擺脫if語句,它看起來像一個緊密的循環。 – WalterM
@WalterM我更新了代碼 – gedamial