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
{
classPRogram
{
static private UdpClient udpclient;
static privateipEndPoint 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.}