tcp udp均可以用来网络通信,在使用之前建议先搜索一下相关网络连接的基本知识,可以更好的理解和使用,tcp建议看下如下文章:https://blog.csdn.net/chuangsun/article/details/67640242,建议多搜一下多看看。

直接上正文。。。。。。。。。。。。。。。

(1)socket类

采用socket类,使用最基本的同步方法。

tcp服务端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading; namespace net
{
class Program
{
static void Main(string[] args)
{
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host); //定义侦听端口
//IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8889);
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, );
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipEnd);
socket.Listen();
Console.Write("Waiting for a client\r\n"); //一旦接受连接,创建一个客户端
Socket client = socket.Accept();
IPEndPoint ipEndClient = (IPEndPoint)client.RemoteEndPoint;
Console.Write("已连接:IP: {0} 端口: {1}\r\n", ipEndClient.Address, ipEndClient.Port); while(true)
{
//接收数据
byte[] recv1 = new byte[];
int count1 = client.Receive(recv1);
string str = Encoding.ASCII.GetString(recv1, , count1);
Console.WriteLine("Client:" + Encoding.ASCII.GetString(recv1, , count1)); if(str=="exit")
{
break;
} //发送数据
string welcome = "Server received:"+ str;
byte[] data = new byte[];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
} Thread.Sleep();
Console.Write("\r\n断开连接: {0}", ipEndClient.Address);
client.Close();
socket.Close();
Console.ReadKey();
}
}
}

tcp客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Threading; namespace client
{
class Program
{
static void Main(string[] args)
{
//定义主机的IP及端口
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEnd = new IPEndPoint(ip, );
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipEnd); while(true)
{
//发送数据
string msg = Console.ReadLine();
byte[] msgBytes = new byte[];
msgBytes = Encoding.ASCII.GetBytes(msg);
socket.Send(msgBytes, msgBytes.Length, SocketFlags.None); //接收数据
byte[] recvMsg = new byte[];
int count = socket.Receive(recvMsg);
string recvStr = Encoding.ASCII.GetString(recvMsg, , count);
Console.WriteLine(recvStr); if(msg=="exit")
{
break;
}
} Thread.Sleep();
Console.Write("断开连接");
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Console.ReadKey();
} }
}

udp服务端:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace UDP
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[]; IPEndPoint ip = new IPEndPoint(IPAddress.Any, );
Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Server.Bind(ip);
Console.WriteLine("Server ready!"); //得到客户机IP
//IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
//EndPoint Remote = (EndPoint)(sender);
//recv = Server.ReceiveFrom(data, ref Remote);
//Console.Write("Message from "+Remote.ToString()+":");
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); ////客户机连接成功后,发送信息
//string welcome = "Hello ! ";
//data = Encoding.ASCII.GetBytes(welcome);
//Server.SendTo(data, data.Length, SocketFlags.None, Remote); while(true)
{
//得到客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, );
EndPoint Remote =sender;
recv = Server.ReceiveFrom(data, ref Remote);
string recvStr = Encoding.ASCII.GetString(data, , recv);
Console.Write("Message from " + Remote.ToString() + ":");
Console.WriteLine(recvStr); //客户机连接成功后,发送信息
string welcome = "Server received: "+ recvStr;
data = Encoding.ASCII.GetBytes(welcome);
Server.SendTo(data, data.Length, SocketFlags.None, Remote);
}
//while (true)
//{
// data = new byte[1024];
// //发送接收信息
// recv = Server.ReceiveFrom(data, ref Remote);
// Console.Write("Message from " + Remote.ToString() + ":");
// Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); // if (Encoding.ASCII.GetString(data, 0, recv) == "exit")
// break; // Server.SendTo(data, recv, SocketFlags.None, Remote);
//}
//Console.WriteLine("停止");
Server.Close();
Console.ReadKey();
}
}
}

udp客户端:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace UDPClient
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[];
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.8.15"), );
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.WriteLine("Client ready:"); //string welcome = "Server hello!";
//data = Encoding.ASCII.GetBytes(welcome);
//server.SendTo(data, data.Length, SocketFlags.None, ip); //IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
//EndPoint Remote = (EndPoint)sender;
//data = new byte[1024];
//int recv = server.ReceiveFrom(data, ref Remote);
//Console.Write("Message from "+Remote.ToString()+":");
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); while(true)
{
string welcome = Console.ReadLine();
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ip); IPEndPoint sender = new IPEndPoint(IPAddress.Any, );
EndPoint Remote = sender;
data = new byte[];
int recv = server.ReceiveFrom(data, ref Remote);
Console.Write("Message from " + Remote.ToString() + ":");
Console.WriteLine(Encoding.ASCII.GetString(data, , recv));
}
//while (true)
//{
// input = Console.ReadLine();
// server.SendTo(Encoding.ASCII.GetBytes(input), Remote); // if (input == "exit")
// break; // data = new byte[1024];
// recv = server.ReceiveFrom(data, ref Remote);
// stringData = Encoding.ASCII.GetString(data, 0, recv);
// Console.Write("Message from " + Remote.ToString() + ":");
// Console.WriteLine(stringData);
//}
Console.WriteLine("停止");
server.Close();
Console.ReadKey();
}
}
}

(2)TcpClient UdpClient TcpListener类

上述连个类为.NET自封装两个类。

tcp服务端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace TcpServerT
{
class Program
{
static void Main(string[] args)
{
//IPAddress IP = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(IPAddress.Any, );
listener.Start();
Console.WriteLine("开始监听:"); //此处也可以采用socket 接收,可以方便进行socket操作
//Socket s = listener.AcceptSocket();
TcpClient client = listener.AcceptTcpClient();//接受一个Client
Console.WriteLine("已连接:");
NetworkStream stream = client.GetStream();//获取网络流
Console.WriteLine("获取连接流:");
string receiveString = ""; while (true)
{
byte[] buffer = new byte[client.ReceiveBufferSize];
stream.Read(buffer, , buffer.Length);//读取网络流中的数据
receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串
//StreamReader sr = new StreamReader(stream);
//receiveString = sr.ReadToEnd(); string sendMsg = "Server received:" + receiveString;
byte[] sendBytes = Encoding.Default.GetBytes(sendMsg);
stream.Write(sendBytes, , sendBytes.Length);
stream.Flush(); Console.WriteLine(receiveString);
//Console.WriteLine("While++");
if (receiveString == "exit")
{
stream.Close();//关闭流
client.Close();//关闭Client
break;
}
}
listener.Stop();
}
}
}

tcp客户端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace TcpClientT
{
class Program
{
static void Main(string[] args)
{
//IPAddress IP = IPAddress.Parse("192.168.8.15");
//IPEndPoint ip = new IPEndPoint(IP, 1234);
//TcpClient client = new TcpClient("192.168.8.15",1234);
IPEndPoint ip = new IPEndPoint(IPAddress.Any, );
TcpClient client = new TcpClient("127.0.0.1", ); NetworkStream sendStream = client.GetStream(); while (true)
{
string msg = Console.ReadLine();
Byte[] sendBytes = Encoding.Default.GetBytes(msg);
sendStream.Write(sendBytes, , sendBytes.Length);
sendStream.Flush();
//StreamWriter sw = new StreamWriter(sendStream);
//sw.WriteLine(msg);
//sw.Flush(); byte[] buffer = new byte[client.ReceiveBufferSize];
sendStream.Read(buffer, , buffer.Length);//读取网络流中的数据
string receiveMsg = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串 Console.WriteLine(receiveMsg); if (msg == "exit")
{
sendStream.Close();//关闭网络流
break;
}
}
client.Close();//关闭客户端
}
}
}

udp服务端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace UdpServer
{
class Program
{
static void Main(string[] args)
{
UdpClient udpServer = new UdpClient(); while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, );
byte[] recvData = udpServer.Receive(ref remoteEP); // listen on port 11000
string recvString = Encoding.Default.GetString(recvData);
Console.Write("Source from" + remoteEP.ToString()+":"+ recvString); if(recvString=="exit")
{
break;
} string sendString = "Server received:" + recvString;
byte[] sendData = Encoding.Default.GetBytes(sendString);
udpServer.Send(sendData, sendData.Length, remoteEP); // reply back
}
udpServer.Close();
}
}
}

udp客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text; namespace UdpClientT
{
class Program
{
static void Main(string[] args)
{
UdpClient client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), ); // endpoint where server is listening
client.Connect(ep); while(true)
{
string sendString = Console.ReadLine();
byte[] sendData = Encoding.Default.GetBytes(sendString);
client.Send(sendData, sendData.Length); byte[] recvData = client.Receive(ref ep);
string recvString = Encoding.Default.GetString(recvData);
Console.WriteLine(recvString); if (sendString == "exit") break;
}
client.Close();
}
}
}

PS:最基本的同步方法为阻塞线程模式,即在接受消息或者服务端等待连接过程中,主程序在此位置属于阻塞(卡住)状态,只有这一步执行完毕(收到消息或者建立连接)才会进行下一步。所以可以通过死循环来实现循环接受消息。

udp不存在严格意义上的客户端服务端,只是要确定消息发送的目标主机

如            Socket client = socket.Accept();

int count1 = client.Receive(recv1);

TCP UDP基本编程(一)的更多相关文章

  1. 三十天学不会TCP,UDP/IP编程--MAC地址和数据链路层

    这篇文章主要是来做(da)推(guang)介(gao)的!由于这两年接触到了比较多的这方面的知识,不想忘了,我决定把他们记录下来,所以决定在GitBook用半年时间上面写下来,这是目前写的一节,后面会 ...

  2. Go语言TCP/UDP Socket编程

    1. TCP编程 TCPClient // TCPClient project main.go package main import ( "fmt" "net" ...

  3. tcp/udp socket编程异同

    一.TCP与UDP的区别 基于连接与无连接 对系统资源的要求(TCP较多,UDP少) UDP程序结构较简单 流模式与数据报模式 TCP保证数据正确性,UDP可能丢包 TCP保证数据顺序,UDP不保证 ...

  4. TCP/UDP网络编程的基础知识与基本示例(windows和Linux)

    一.TCP编程的一般步骤 服务器端: 1.创建一个socket,用函数socket() 2.绑定IP地址.端口等信息到socket上,用函数bind() 3.开启监听,用函数listen() 4.接收 ...

  5. Java中的TCP/UDP网络通信编程

    127.0.0.1是回路地址,用于测试,相当于localhost本机地址,没有网卡,不设DNS都可以访问. 端口地址在0~65535之间,其中0~1023之间的端口是用于一些知名的网络服务和应用,用户 ...

  6. Java TCP/UDP网络通信编程

    本文转自:http://www.cnblogs.com/cdtarena/archive/2013/04/10/3012282.html 网络应用中基本上都是TCP(Transmission Cont ...

  7. 自测之Lesson15:TCP&UDP网络编程

    题目:编写一个TCP通信的程序. 实现代码: #include <stdio.h> #include <sys/socket.h> #include <unistd.h& ...

  8. tcp udp socket编程

    http://blog.csdn.net/ns_code/article/details/14128987

  9. 三十天学不会TCP,UDP/IP网络编程-IP头格式祥述

    我又来了,这篇文章还是来做(da)推(guang)介(gao)我自己的!俗话说事不过三,我觉得我下次得换个说法了,不然估计要被厌恶了,但是我是好心呐,一定要相信我纯洁的眼神.由于这两年接触到了比较多的 ...

随机推荐

  1. 原来python如此神奇

    一.优缺点分析 1.缺点: ① 数学问题的生成中只考虑了消除乘除法加括号的无效情况(例如3*(4+5)或(6*5)/2这样的计算),但没有去掉加减法加括号的无效情况(例如(4+(7+8))或(3-(2 ...

  2. java架构之路-(分布式)初识zookeeper安装与参数详解

    ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件.它是一个为分布式应用提供一致性服务的软件,提供的功 ...

  3. 读取unicode日志文件并清除记录的垃圾文件

    //读取unicode文件,并清除记录的垃圾文件 //参数1:日志文件路径 bool ReadFilePath(const wchar_t *DataFilePath) { wchar_t ChBuf ...

  4. 夯实Java基础系列15:Java注解简介和最佳实践

    Java注解简介 注解如同标签 Java 注解概述 什么是注解? 注解的用处 注解的原理 元注解 JDK里的注解 注解处理器实战 不同类型的注解 类注解 方法注解 参数注解 变量注解 Java注解相关 ...

  5. PHP5.5 mysqli如何连接MySQL数据库和读取数据

    在学习 1. 开启PHP的API支持 (1)首先修改您的php.ini的配置文件.查找下面的语句:;extension=php_mysqli.dll将其修改为:extension=php_mysqli ...

  6. 在 Cocos Creator 中使用 Protobufjs(一)

    一. 环境准备 我一直在探索Cocos H5正确的开发姿势,目前做javascript项目已经离不开 nodejs.npm或grunt等脚手架工具了. 1.初始化package.json文件 npm ...

  7. [Git] Git 使用记录

    1. 配置git客户端 1.1 安装git bash https://git-scm.com/downloads 1.2 设置ssh Key 查看是否有ssh key ls -al ~/.ssh 没有 ...

  8. 浅谈个人对客户端JavaScript同步、异步、执行顺序等概念的理解

    一.同步和异步的概念. 同步:即按代码的顺序执行任务. 在下列代码中,按照同步概念,则是先打印1后打印2. console.log(1); console.log(2); 异步:即执行一个任务的同时执 ...

  9. vue 上传文件 和 下载文件 面试的时候被问到过

    Vue上传文件,不必使用什么element 的uplaod, 也不用什么npm上找的个人写的包,就用原生的Vue加axios就行了, 废话不多说,直接上代码:html: <input type= ...

  10. LeetCode_20-Valid Parentheses

    给定一个字符串,其中包含字符’(’,’)’,’[’,’]’,’{‘,’}’,左括号必须匹配右括号,一对匹配的括号不能单独出现单个左括号或者右括号.如:(()[])有效,[(])无效空字符串也算是有效的 ...