简单使用SOCKET,TCP,UDP模式之间的通信
TCP与UDP区别
TCP---传输控制协议,提供的是面向连接、可靠的字节流服务。当客户和服务器彼此交换数据前,必须先在双方之间建立一个TCP连接,之后才能传输数据。TCP提供超时重发,丢弃重复数据,检验数据,流量控制等功能,保证数据能从一端传到另一端。 UDP---用户数据报协议,是一个简单的面向数据报的运输层协议。UDP不提供可靠性,它只是把应用程序传给IP层的数据报发送出去,但是并不能保证它们能到达目的地。由于UDP在传输数据报前不用在客户和服务器之间建立一个连接,且没有超时重发等机制,故而传输速度很快
有人说TCP就像打电话,必须接通后才能通信,而UDP就像发短信一样,不需要接通就可以发送。比喻甚是恰当啊。
内容大部分来源于网络,不喜勿喷啊!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace SocketClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
} private void button1_Click(object sender, EventArgs e)
{
IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(textBox2.Text)); if (comboBox1.SelectedItem.ToString() == "TCP")
{
TcpServer(serverIP);
}
else if (comboBox1.SelectedItem.ToString() == "UDP")
{
UdpClient(serverIP);
}
} #region TCP连接方式
/// <summary>
/// TCP连接方式
/// </summary>
/// <param name="serverIP"></param>
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void TcpServer(IPEndPoint serverIP)
{
listBox1.Items.Add("客户端启动TCP连接模式");
try
{
tcpClient.Connect(serverIP);//连接
button1.Enabled = false;
button1.BackColor = Color.Red;
textBox1.Enabled = false;
comboBox1.Enabled = false;
textBox2.Enabled = false;
}
catch (SocketException e)
{
listBox1.Items.Add(string.Format("连接出错:{0}", e.Message)); return;
} listBox1.Items.Add("客户端:client-->server");
new Thread(() =>
{
while (true)
{
byte[] data = new byte[];
try
{
int length = tcpClient.Receive(data); }
catch (Exception ex)
{
//listBox1.Items.Add("出现异常");
break;
}
listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
}
}).Start();
}
#endregion #region UDP连接方式
/// <summary>
/// UDP连接方式
/// </summary>
/// <param name="serverIP"></param>
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
public void UdpClient(IPEndPoint serverIP)
{
listBox1.Items.Add("客户端启动UDP模式");
udpClient.SendTo(Encoding.UTF8.GetBytes(textBox3.Text), SocketFlags.None, serverIP);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, );
EndPoint Remote = (EndPoint)sender;
button1.Enabled = false;
button1.BackColor = Color.Red;
textBox1.Enabled = false;
comboBox1.Enabled = false;
textBox2.Enabled = false;
new Thread(() =>
{
while (true)
{
byte[] data = new byte[];
try
{
int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
}
catch (Exception ex)
{
// listBox1.Items.Add(string.Format("出现异常:{0}", ex.Message));
break;
}
listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
}
}).Start(); }
#endregion private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString()=="TCP")
{
tcpClient.Send(Encoding.UTF8.GetBytes(textBox3.Text));
listBox1.Items.Add(string.Format("{0}发送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text));
}
else if(comboBox1.SelectedItem.ToString()=="UDP")
{ listBox1.Items.Add(string.Format("{0}发送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text));
} } private void button3_Click(object sender, EventArgs e)
{
tcpClient.Close();
udpClient.Close();
Application.Exit(); }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace SocketClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
} private void button1_Click(object sender, EventArgs e)
{
IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(textBox2.Text)); if (comboBox1.SelectedItem.ToString() == "TCP")
{
TcpServer(serverIP);
}
else if (comboBox1.SelectedItem.ToString() == "UDP")
{
UdpClient(serverIP);
}
} #region TCP连接方式
/// <summary>
/// TCP连接方式
/// </summary>
/// <param name="serverIP"></param>
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void TcpServer(IPEndPoint serverIP)
{
listBox1.Items.Add("客户端启动TCP连接模式");
try
{
tcpClient.Connect(serverIP);//连接
button1.Enabled = false;
button1.BackColor = Color.Red;
textBox1.Enabled = false;
comboBox1.Enabled = false;
textBox2.Enabled = false;
}
catch (SocketException e)
{
listBox1.Items.Add(string.Format("连接出错:{0}", e.Message)); return;
} listBox1.Items.Add("客户端:client-->server");
new Thread(() =>
{
while (true)
{
byte[] data = new byte[];
try
{
int length = tcpClient.Receive(data); }
catch (Exception ex)
{
//listBox1.Items.Add("出现异常");
break;
}
listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
}
}).Start();
}
#endregion #region UDP连接方式
/// <summary>
/// UDP连接方式
/// </summary>
/// <param name="serverIP"></param>
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
public void UdpClient(IPEndPoint serverIP)
{
listBox1.Items.Add("客户端启动UDP模式");
udpClient.SendTo(Encoding.UTF8.GetBytes(textBox3.Text), SocketFlags.None, serverIP);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, );
EndPoint Remote = (EndPoint)sender;
button1.Enabled = false;
button1.BackColor = Color.Red;
textBox1.Enabled = false;
comboBox1.Enabled = false;
textBox2.Enabled = false;
new Thread(() =>
{
while (true)
{
byte[] data = new byte[];
try
{
int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
}
catch (Exception ex)
{
// listBox1.Items.Add(string.Format("出现异常:{0}", ex.Message));
break;
}
listBox1.Items.Add(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
}
}).Start(); }
#endregion private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString()=="TCP")
{
tcpClient.Send(Encoding.UTF8.GetBytes(textBox3.Text));
listBox1.Items.Add(string.Format("{0}发送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text));
}
else if(comboBox1.SelectedItem.ToString()=="UDP")
{ listBox1.Items.Add(string.Format("{0}发送消息:{1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), textBox3.Text));
} } private void button3_Click(object sender, EventArgs e)
{
tcpClient.Close();
udpClient.Close();
Application.Exit(); }
}
}
感谢园友
http://www.cnblogs.com/hongfei/archive/2012/12/08/2808771.html
http://www.cnblogs.com/zengqinglei/archive/2013/04/27/3046119.html
http://zhidao.baidu.com/link?url=HNMpttFbHTevgWwye0rPGiGuQGihHOaNNKbpJZ7CvEn8YjWr2w_5Ok_YUx1xd73yxTt9k6STVaMMuzuGINqQKK
简单使用SOCKET,TCP,UDP模式之间的通信的更多相关文章
- 27.Socket,TCP,UDP,HTTP基本通信原理
Socket,TCP,UDP,HTTP基本通信原理(摘自百度): TCP.UDP,HTTP 底层通信都是通过 socket 套接字实现 网络上不同的计算机,也可以通信,那么就得使用网络套接字(sock ...
- ActionScript简单实现Socket Tcp应用协议分析器
转自..smark http://www.cnblogs.com/smark/archive/2012/05/15/2501507.html ActionScript简单实现Socket Tcp应用协 ...
- 网络编程 套接字socket TCP UDP
网络编程与套接字 网络编程 网络编程是什么: 网络通常指的是计算机中的互联网,是由多台计算机通过网线或其他媒介相互链接组成的 编写基于网络的应用程序的过程序称之为网络编程. 网络编程最主要的工 ...
- SOCKET, TCP/UDP, HTTP, FTP 浅析
SOCKET, TCP/UDP, HTTP, FTP (一)TCP/UDP,SOCKET,HTTP,FTP简析 TCP/IP是个协议组,可分为三个层次:网络层.传输层和应用层: 网络层:IP协议. ...
- 网络编程之socket(TCP,UDP)
socket层 tcp协议和udp协议 1)Socket服务器编程 主要包括下面的几步: 1.打开socket 2.绑定到一个地址和端口 3.侦听进来的连接 4.接受连接 5.读写数据 (2)Sock ...
- UNP学习笔记2——从一个简单的ECHO程序分析TCP客户/服务器之间的通信
1 概述 编写一个简单的ECHO(回复)程序来分析TCP客户和服务器之间的通信流程,要求如下: 客户从标准输入读入一行文本,并发送给服务器 服务器从网络输入读取这个文本,并回复给客户 客户从网络输入读 ...
- day29 python 套接字socket TCP udp 形式发送信息的区别
我们经常把socket翻译为套接字,socket是在应用层和传输层之间的一个抽象层,它把TCP/IP层复杂的操作抽象为几个简单的接口供应用层调用已实现进程在网络中通信. socket起源于UNIX,在 ...
- iOS socket TCP UDP
TCP: 服务器: #import <Foundation/Foundation.h> #include <sys/socket.h> #include <netinet ...
- Socket TCP/UDP
TCP TCPClient package com.tcp; import java.io.*; import java.net.*; class TCPClient { public static ...
随机推荐
- js 数组过滤 filter
let res = this.list.filter(item => routeEqual(this.currentRouteObj, item) || item.name === this.$ ...
- 【vc】高精度时间函数的使用
方法一: 函数定义如下: int UsSleep(int us);//返回实际的微秒延时时间 代码实现如下: //参数一表示 需要等待的时间 微秒为单位 int UsSleep(int us) { / ...
- Linux-fuser
Linux-fuser 1. 描述 2. 选项3. EXAMPLES4. RESTRICTIONS 限制5. SIGNAL 可用信号 fuser - 使用文件或套接字识别进程 1. 描述 fuser使 ...
- java面试宝典第一弹
object类的直接子类有哪些 Boolean Character Character.Subset Class ClassLoader Compiler Enum Math Number Packa ...
- [LOJ] 分块九题 5
区间开平方,区间查询. lazy标记改为区间是否全是1或者0,这样的区间是没有更新价值的. //Stay foolish,stay hungry,stay young,stay simple #inc ...
- tornado框架基础10-websocket
websocket 01 长轮询 在网页,我们经常扫码登录,结合之前的学习的知识点,来思考下,前端是如何知道用户在手机上扫码登录了呢? 长轮询:客户端不断的向服务器发送请求 缺点: \1. 开销大 \ ...
- Servlet+JSP教程之:第一个Web程序
我们知道当浏览器发送请求给服务器后,服务器会调用并执行对应的逻辑代码进行请求处理.逻辑代 码是由程序员自己编写然后放进服务器进行运行,其实就是Servlet程序. 第一个Web程序: 开发工具: My ...
- idea 中使用 出现 svn: E155036
在idea中使用svn checkout时 svn出现如上错误. 原因本地的工作副本太旧.command line进入本地工作副本的根目录,执行svn upgrade后 重启idea就可以了.
- Python 单向队列Queue模块详解
Python 单向队列Queue模块详解 单向队列Queue,先进先出 '''A multi-producer, multi-consumer queue.''' try: import thread ...
- CLR Via CSharp读书笔记(26) - 计算限制的异步操作
执行上下文: 执行上下文包括安全设置(压缩栈.Thread的Principal属性和Windows身份),宿主设置(System.Threading.HostExecutionContextManag ...