UDP通信:
服務端&客戶端 端口號不一樣,其他部分一樣。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Consoleapplication23
{
class PRogram
{
static private UdpClient udpclient;
static private ipEndPoint targetpoint;
static void Main(string[] args)
{
IPEndPoint udppoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
udpclient = new UdpClient(udppoint);
targetpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666);
Thread t1 = new Thread(new ThreadStart(thread1));
t1.Start();
string c;
c = Convert.ToString(Console.ReadLine());
while (true)
{
if (c != "!")
{
byte[] ch = Encoding.UTF8.GetBytes(c);
udpclient.Send(ch, ch.Length, targetpoint);
c = Convert.ToString(Console.ReadLine());
}
}
}
public static void thread1()
{
//IPEndPoint targetpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777);
//UdpClient server = new UdpClient(targetpoint);
//IPEndPoint senderpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
while (true)
{
byte[] lw = udpclient.Receive(ref targetpoint);
Console.WriteLine("2號說:{0}", Encoding.UTF8.GetString(lw));
}
}
}
}
TCP通信:
服務端:
1.using System;
2.using System.Collections.Generic; 3.using System.Linq; 4.using System.Text; 5.using System.Net; 6.using System.Net.Sockets; 7. 8.namespace Demo 9.{ 10. class Program 11. { 12. static void Main(string[]args) 13. { 14. byte[]SendBuf = Encoding.UTF8.GetBytes("Hello,Client!"); //發給客戶端的消息; 15. IPEndPointlocalEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"),6666); //本地端地址 16. TcpListenerListener = new TcpListener(localEP); //建立監聽類,并綁定到指定的端地址 17. Listener.Start(10); //開始監聽 18. Console.WriteLine("Server is listening..."); 19. TcpClientremoteClient = Listener.AcceptTcpClient(); //等待連接(阻塞) 20. Console.WriteLine("Client:{0} connected!",remoteClient.Client.RemoteEndPoint.ToString()) ; //打印客戶端連接信息; 21. remoteClient.Client.Send(SendBuf); //發送歡迎信息; 22. remoteClient.Close(); //關閉連接; 23. } 24. } 25.}
客戶端:
1.using System;
2.using System.Collections.Generic; 3.using System.Linq; 4.using System.Text; 5.using System.Net; 6.using System.Net.Sockets; 7. 8.namespace Demo_Client 9.{ 10. class Program 11. { 12. static void Main(string[] args) 13. { 14. byte[] RecvBuf=new byte[1024]; //申請接收緩存; 15. int RecvBytes = 0; //接收字節數; 16. string recvmsg=null; //接收消息; 17. 18. IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666); //遠程服務器端地址; 19. TcpClient remoteServer = new TcpClient(); //創建TCPClient類來與服務器通信; 20. remoteServer.Connect(remoteEP); //調用connect方法連接遠端服務器; 21. Console.WriteLine("I'm using {0}.", remoteServer.Client.LocalEndPoint); //打印自己使用的端地址; 22. RecvBytes=remoteServer.Client.Receive(RecvBuf); //接受服務器發送過來的消息; 23. recvmsg=Encoding.UTF8.GetString(RecvBuf,0,RecvBytes); //將接受到的字節碼轉化為string類型; 24. Console.WriteLine("Server says:{0}.", recvmsg); //打印歡迎信息; 25. } 26. } 27.}
新聞熱點
疑難解答