0
即時通訊新的C#套接字編程和即時通訊工作的服務器,爲某些客戶端發送字符串的小項目。我通過修改了MSDN's Synchronous Server和client套接字示例。 當我在同一臺計算機上運行服務器和客戶端時,它們工作正常,但是當我在另一臺計算機上運行服務器和客戶端時,客戶端上顯示套接字異常(兩臺計算機都在同一網絡上) 。 現在我不知道該怎麼辦:端口轉發?更改代碼?C#套接字:客戶端沒有連接到服務器分離計算機
服務器代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace textweb
{
class Program
{
static int counter = 0;
static Socket[] _socket = new Socket[2];
static void Main(string[] args)
{
byte[] bytes = new Byte[1024];
//running the server on the local host
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
Console.WriteLine(ipHostInfo.HostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress);
TcpListener listener = new TcpListener(ipAddress, /*MyPort*/);
try
{
listener.Start(10);
Console.WriteLine("Waiting for a connection...");
while (counter < 2)
{
while (!listener.Pending()) { }
while (listener.Pending())
{
_socket[counter] = listener.AcceptSocket();
counter++;
}
}
bool _continue = true;
while (_continue)
{
string m = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(m);
foreach (Socket soc in _socket)
{
soc.Send(msg);
if (m == "exit")
{
soc.Shutdown(SocketShutdown.Both);
soc.Close();
_continue = false;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
客戶端代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace textclient
{
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
try {
IPHostEntry ipHostInfo = Dns.GetHostByName(/*server's ip*/);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,/*MyPort*/);
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",sender.RemoteEndPoint.ToString());
bool _continue = true;
while (_continue)
{
if (sender.Available>0)
{
int bytesRec = sender.Receive(bytes);
string a = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine(a);
if (a == "exit")
{
sender.Shutdown(SocketShutdown.Both);
sender.Close();
_continue = false;
}
}
}
Console.ReadKey();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
Console.ReadKey();
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}", se.ToString());
Console.ReadKey();
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
Console.ReadKey();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
Console.ReadKey();
}
}
}
}
我希望這個問題是清楚的,你會回答這個問題, 伊泰