我制作了一个非常简单的客户端>服务器程序,它可以正常工作,但有时它会不时地连接到服务器,但在其他情况下它需要超过20秒或根本不会连接。即使我在SAME PC上启动客户端和服务器,也会发生这种情况。
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace TCPListener
{
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect("95.102.185.157", 8001);
Console.WriteLine("Connected");
string message = Console.ReadLine();
NetworkStream stream = client.GetStream();
ASCIIEncoding ncoder = new ASCIIEncoding();
Byte[] transfer = ncoder.GetBytes(message);
stream.Write(transfer, 0, transfer.Length);
client.Close();
Console.ReadKey();
}
}
}
服务器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("192.168.1.12");
TcpListener listener = new TcpListener(ip, 8001);
listener.Start();
Console.WriteLine("Listening on " + ip.ToString());
Socket s = listener.AcceptSocket();
Console.WriteLine("Recieved socket" + s.RemoteEndPoint);
Byte[] b = new Byte[100];
s.Receive(b);
foreach (Byte byt in b)
{
Console.Write(Convert.ToChar(byt));
}
ASCIIEncoding ncoder = new ASCIIEncoding();
Byte[] message = ncoder.GetBytes("cud");
s.Send(message);
s.Close();
listener.Stop();
Console.ReadKey();
}
}
}