先來講述下我自己對于整個Socket通信過程的理解,畢竟初學(xué),說錯見諒,知道錯了會改正~
首先在服務(wù)端新建一個serverSocket,對其進(jìn)行初始化(一般包含AddressFamily:IP地址類型,SocketType:Socket傳輸數(shù)據(jù)方式,ProtoType:傳輸協(xié)議);
接著我們要設(shè)置server端要綁定的IP:port;然后開始監(jiān)聽,并設(shè)置最多同時監(jiān)聽多少個Client.
這時,服務(wù)端就在等待狀態(tài),直到某一個Client連接到這個ip:port上,這時serverSocket.Accept()工作,獲得這個連接。(此時的連接是有地址信息的哦!記得保存)
獲得連接之后,server就可以和這個Client進(jìn)行通信了,當(dāng)加入第二個Client(我們稱其為ClientB)時,Server接收到ClientB的消息,可以將這個消息轉(zhuǎn)發(fā)給前一個Client(我們稱其為ClientA),當(dāng)受到ClientA的消息,也可以轉(zhuǎn)發(fā)給ClientB。這樣就實現(xiàn)了Clients之間的通信了。(重點在保存連接信息?。。?br />
那么現(xiàn)在貼上代碼講解:
Server端代碼
namespace SocketServer
{
class Program
{
private static byte[] result = new byte[1024];
static Socket serverSocket;
private static string client;
private static Socket clientSocket;
//我這里存了兩個Client,因為自己電腦開了兩個Client,不會有多的
//理論上應(yīng)該開一個Socket[]來保存信息,最好用一個二元組將client的信息和連接綁定起來
//這樣就可以實現(xiàn)斷開連接后下次登陸還是可以識別是這個Client
private static Socket clientSocketA=null;
private static Socket clientSocketB=null;
static void Main(string[] args)
{
Program.SetPort(8885);
}
private static void SetPort(int port)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");//set ip
serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);//initialize
serverSocket.Bind(new IPEndPoint(ip, port));//bind
serverSocket.Listen(10);
//進(jìn)入監(jiān)聽狀態(tài)
Console.WriteLine("監(jiān)聽{0}成功", serverSocket.LocalEndPoint.ToString());
//開啟一個線程來監(jiān)聽客戶端連接
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// summary>
/// 監(jiān)聽客戶端連接
/// /summary>
private static void ListenClientConnect()
{
while (true)
{
//Client連接上后 得到這個連接
clientSocket = serverSocket.Accept();
//這里我因為只有兩個Client,所以就簡單寫了
if (clientSocketA == null)
{
clientSocketA = clientSocket;
}
else if (clientSocketB == null)
{
clientSocketB = clientSocket;
}
else
{
//當(dāng)其中一個斷開了,又重新連接時,需要再次保存連接
if (clientSocketB.IsBound)
{
clientSocketA = clientSocketB;
clientSocketB = clientSocket;
}
else
{
clientSocketB = clientSocketA;
clientSocketA = clientSocket;
}
}
clientSocket.Send(Encoding.ASCII.GetBytes("say hello"));
//開個線程接收Client信息
Thread receivedThread = new Thread(ReceiveMessage);
receivedThread.Start(clientSocket);
}
}
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket) clientSocket;
while (true)
{
try
{
int revceiveNumber = myClientSocket.Receive(result);
//Console.WriteLine("接受客戶端{(lán)0}消息{1}", myClientSocket.RemoteEndPoint.ToString()
// , Encoding.ASCII.GetString(result, 0, revceiveNumber));
Console.WriteLine(Encoding.ASCII.GetString(result, 0, revceiveNumber));
if (myClientSocket == clientSocketA)
{
Console.WriteLine("receive from A");
if (clientSocketB!=nullclientSocketB.IsBound)
{
Console.WriteLine("a IS BOUND");
clientSocketB.Send(result, 0, revceiveNumber, SocketFlags.None);
}
else
{
myClientSocket.Send(Encoding.ASCII.GetBytes("the people is not online! Send Failed!"));
Console.WriteLine("對方不在線上,發(fā)送失??!");
}
}
else
{
Console.WriteLine("receive from B");
if (clientSocketA != null clientSocketA.IsBound)
{
Console.WriteLine("a IS BOUND");
clientSocketA.Send(result, 0, revceiveNumber, SocketFlags.None);
}
else
{
myClientSocket.Send(Encoding.ASCII.GetBytes("the people is not online! Send Failed!"));
Console.WriteLine("對方不在線上,發(fā)送失?。?);
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
Client端代碼(因為都差不多 就只貼一個了)
namespace SocketClient
{
class Program
{
private static byte[] result = new byte[1024];
private static Socket clientSocket;
private static void ListenServer()
{
while (true)
{
result = new byte[1024];
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
}
}
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(ip, 8885);
Console.WriteLine("連接成功!");
}
catch (Exception e)
{
Console.WriteLine("連接失?。?);
return;
}
Thread threadRead = new Thread(ListenServer);
threadRead.Start();
while(true)
{
try
{
Thread.Sleep(1000);
string sendMessage = Console.ReadLine();
clientSocket.Send(Encoding.ASCII.GetBytes("Sylvia:"+sendMessage));
}
catch (Exception ex)
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("發(fā)送完畢 按回車退出");
Console.ReadKey();
}
}
}
寫的時候要特別注意一下Send信息的時候,注意byte[]的傳輸大小,很容易變成byte[]數(shù)組的大小而不是內(nèi)容的大小。
這個大家就自己嘗試吧。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- C#基于TCP協(xié)議的服務(wù)器端和客戶端通信編程的基礎(chǔ)教程
- C#實現(xiàn)的Socket服務(wù)器端、客戶端代碼分享
- c#多線程網(wǎng)絡(luò)聊天程序代碼分享(服務(wù)器端和客戶端)
- C#串口通信程序?qū)嵗斀?/li>
- C#實現(xiàn)Socket通信的解決方法
- C#中使用UDP通信實例
- C#中異步Socket通信編程代碼實例
- C#串口通信實現(xiàn)方法
- c#實現(xiàn)簡單控制臺udp異步通信程序示例