我需要創建一個應用程序以將所有連接到套接字服務器的客戶的時間返回給我。 但我的應用程序只能在本地進行通信。C#套接字服務器只在本地進行通信
例子:
如果端點服務器是:(192.168.0.1,32000)
客戶終端是:(192.168.0.1,32000)
它們連接和comunnicate。
但
如果端點服務器是:(192.168.0.1,32000)
客戶終端是:(192.168.0.2,32000)
它們連接,但不comunnicate。
服務器代碼:
class Server:Sincronia
{
GetIP getip = new GetIP();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private List<Socket> ListaDeClientesSockets = new List<Socket>(); /*Lista de sockets para adicionar clientes*/
private List<string> ListaDeClients = new List<string>();
private List<string> ListaDeHoras = new List<string>();
private const int _BUFFER_SIZE = 2048;
private int _PORT;
private string Ip;
private byte[] _buffer = new byte[_BUFFER_SIZE];
public Server(string IP, int port) /*Construtor para inicialização do IP e da Porta*/
{
this.Ip = IP;
this._PORT = port;
}
public void Connect()
{
Console.WriteLine("Socket Server ON");
Console.WriteLine(getip.getIP());
_serverSocket.Bind(new IPEndPoint(IPAddress.Parse(getip.getIP()), _PORT));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(AcceptCallback, null);
}
public void ShowAllClients()
{
Console.WriteLine("####################### " + ListaDeClientesSockets.Count + " #######################");
for (int i = 0; i < ListaDeClientesSockets.Count; i++)
{
int j = i + 1;
Console.WriteLine("Client : " + j + " IP : " + ListaDeClients[i]);
}
}
private void CloseConnections()
{
foreach (Socket socket in ListaDeClientesSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
_serverSocket.Close();
}
/// <summary>AcceptCallback método da classe Server
/// Evento realizado para aceitar conexões dos clientes adicionando em uma lista genérica
/// /// </summary>
private void AcceptCallback(IAsyncResult asyncronousResult)
{
Socket socket;
try
{
socket = _serverSocket.EndAccept(asyncronousResult);
}
catch (ObjectDisposedException)
{
return;
}
ListaDeClientesSockets.Add(socket);
ListaDeClients.Add(((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
Console.WriteLine("Client Connect " + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString());
_serverSocket.BeginAccept(AcceptCallback, null);
}
public void SendToALL(string text)
{
foreach(Socket socket in ListaDeClientesSockets.ToList())
{
ListaDeHoras.Clear();
byte[] dataByte = Encoding.ASCII.GetBytes(text);
socket.Send(dataByte);
}
}
/// <summary>ReceiveCallBack método da classe Server
/// Evento realizado para receber e enviar dados do cliente através de um IASyncResult
/// </summary>
private void ReceiveCallback(IAsyncResult asyncronousResult)
{
Socket current = (Socket)asyncronousResult.AsyncState;
int received;
try
{
received = current.EndReceive(asyncronousResult);
}
catch (SocketException) /*Catch realizado caso houver perca de conexão com o cliente*/
{
Console.WriteLine("Conexão com o cliente " + ((IPEndPoint) current.RemoteEndPoint).Address.ToString() + " perdida.");
current.Close();
ListaDeClients.Remove(((IPEndPoint)current.RemoteEndPoint).Address.ToString());
ListaDeClientesSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(_buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
Console.WriteLine("Received Text: " + text);
ListaDeHoras.Add(text);
current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
}
}
程序服務器代碼:
class Program
{
static void Main(string[] args)
{
Console.Title = "Servidor";
Server server = new Server("localhost", 8000);
server.Connect();
while (true)
{
string text = Console.ReadLine();
if (text == "mostrar")
server.ShowAllClients();
else
server.SendToALL(text);
}
Console.ReadKey();
}
}
客戶端代碼:
class Client
{
Socket socketClient;
static int port = 8000;
static string localhostIP = "127.0.0.1";
private const int _BUFFER_SIZE = 2048;
private byte[] _buffer = new byte[_BUFFER_SIZE];
private string IP;
public Client(string ip)
{
this.IP = ip;
}
public void Start()
{
IPEndPoint endp = new IPEndPoint(IPAddress.Parse(IP), port);
try
{
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.BeginConnect(endp, new AsyncCallback(ConnectCALLBACK), socketClient);
Receive(socketClient);
}
catch
{
}
}
private void ConnectCALLBACK(IAsyncResult assynresult)
{
try
{
Socket client = (Socket)assynresult.AsyncState;
Console.WriteLine("Conectado");
client.EndConnect(assynresult);
}
catch(SocketException)
{
Console.WriteLine("Falta de conexão com o servidor, verifique sua conexão.");
}
}
public void Receive(Socket socket)
{
try
{
socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
}
catch
{
}
}
private void ReceiveCallback(IAsyncResult asyncronousResult)
{
Socket current = (Socket)asyncronousResult.AsyncState;
int received;
try
{
received = current.EndReceive(asyncronousResult);
}
catch (SocketException)
{
return;
}
byte[] recBuf = new byte[received];
Array.Copy(_buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
if(text == "clock")
{
string horas = DateTime.Now.ToString("dd-MM-yyyy HH:mm");
byte[] sended = Encoding.ASCII.GetBytes(horas);
current.Send(sended);
}
current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
}
}
我所需要的服務器類型 「時鐘」,這被髮送到所有客戶端。
而且客戶端收到客戶端發送給他們的時間。
取代你的客戶端啓動功能,你有沒有測試了服務器的端口是否是防火牆或只需打開人人網看起來就像你正在使用你的溝通是後面的端口一個防火牆 –
Ja被釋放了門,但它沒有工作。 –
假設您已正確配置服務器和客戶端的IP地址,則會出現網絡配置問題。如果你還沒有,你的代碼中會出現印刷錯誤。無論哪種方式,這個問題都是無關緊要的。如果你相信這是兩種可能性之一以外的東西,請解決你的問題,使其包含一個可靠地再現問題的良好[mcve]。 –