[英]C# Chat Program
當我使用本地計算機托管並連接到它時,它可以 100% 工作,但是當我實時嘗試時(服務器編程位於實際服務器上,客戶端在其他計算機上)它不起作用。 我收到“無法建立連接,因為目標機器主動拒絕它”。 我檢查了它是否在主動監聽(並且服務器上的端口太正確)-它是禁用了所有防火牆,包括路由器[除了嘗試禁用之外,它還有一個規則集允許它]-沒有修復。
這可能是內部網絡問題嗎? 就像它只是不喜歡嘗試連接到本地機器一樣? 我一無所知,沒有其他異常被拋出或任何東西。
服務器代碼
IPAddress ip = IPAddress.Parse("127.0.0.1");
Int32 port = 9818;
TcpListener server = new TcpListener(ip,port);
TcpClient client;try
{
server.Start();
Console.WriteLine("Server Started..");
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
while (true)
{
client = server.AcceptTcpClient();
byte[] recieveBuffer = new byte[100];
byte[] sendBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(recieveBuffer, 0, recieveBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach (byte b in recieveBuffer)
{
if (b.Equals(00))
{
break;
}
else
msg.Append(Convert.ToChar(b).ToString());
}
int byteCount = Encoding.ASCII.GetByteCount(msg.ToString());
byte[] sendData = new byte[byteCount];
stream.Write(sendData, 0, sendData.Length);
Console.WriteLine(msg);}//End while
而客戶是..
public Int32 port = 9818;
public TcpClient client;
public string serverIP = "10.0.0.20";
//public string serverIP = "localhost"; //For testings
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient(serverIP, port);
//Clean up space
int byteCountU = Encoding.ASCII.GetByteCount(txtUser.Text);
int byteCountP = Encoding.ASCII.GetByteCount(txtPassword.Text);
//Send
byte[] sendDataU = new byte[byteCountU];
byte[] sendDataP = new byte[byteCountP];
//Greating should be formated on server's end to not ruin user and password sending
sendDataU = Encoding.ASCII.GetBytes(txtUser.Text);
sendDataP = Encoding.ASCII.GetBytes(txtPassword.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendDataU, 0, sendDataU.Length);
//Close
stream.Close();
client.Close();
對不起,這個格式化界面是我能做的最好的
這是一個網絡問題,而不是編程問題。
作為一般規則,網絡類不關心另一端是否在同一台計算機、同一交換機或 Voyager 2 探測器上。 在那里開辟道路是一個網絡問題,而不是編程問題。
我最好的猜測是 Windows Firefall 有點激進。
附帶說明:異常處理是我的一個小煩惱,而您的則有問題。 這里有兩篇關於我經常鏈接的主題的文章:
您將服務器設置為僅在 localhost (127.0.0.1) 上偵聽。 這意味着只允許和解析本地連接,因此防火牆將在這些連接上禁用,您可以在大多數情況下忽略它。 當您調試應用程序或在同一台機器上進行進程間通信時,它很有用。
要監聽來自其他機器的傳入連接,您應該有足夠的權限並將您的服務器地址設置為 0.0.0.0,即“監聽所有外部連接”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.