简单使用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 ...
随机推荐
- 基于SAE的Python+Django部署
本文主要参考:http://www.cnblogs.com/qtsharp/archive/2012/01/12/2320774.html,另外包括自己的实际操作. 一.申请SAE帐号以及创建应用ya ...
- (转)使用CGLIB实现AOP功能与AOP概念解释
http://blog.csdn.net/yerenyuan_pku/article/details/52864395 使用CGLIB实现AOP功能 在Java里面,我们要产生某个对象的代理对象,这个 ...
- Visual Odometry
http://www.cvlibs.net/datasets/kitti/eval_odometry.php
- Perl中 qw 是 “quoted Word” 或是 “quoted by whitespace”的简写
Perl中 qw 是 “quoted Word” 或是 “quoted by whitespace”的简写 eg: @strict_pragma = qw ( a b c);
- Yii2 advance swiftmailer 不能发送邮件
我用的是Yii2高级模板,在配置好邮箱后,并编写测试,测试结果表明是发送成功的,但我的邮箱就是接受不了邮件. 经过排查发现,是由 common/config/main-local.php 文件的 'u ...
- [LOJ] 分块九题 8
区间查询数值+整体赋值 维护tag代表整个区间被赋成了tag[i] 用pushdown操作,而不是修改了再check. 不压缩代码了,调起来心累,长点有啥不好. //Stay foolish,stay ...
- mysql查询表中最小可用id值
今天在看实验室的项目时,碰到的一个问题,.先把sql语句扔出来 // 这条语句在id没有1时,不能得到正确的查询结果. select min(id+1) from oslist c where not ...
- Python 函数的初识
1.函数的初识 函数的作用:以功能为导向 减少代码重复 # 函数试编程 # 函数以功能(完成一件事)为导向,登录 注册, # 一个函数就是一个功能,一个函数只能写一个功能 # 何时需要 何时调用,随调 ...
- solr 时区问题
本人使用solr版本5.0.0,使用jetty启动 solr默认UTC时区,与我们相差八小时,按照网络上资料修改 C:\Users\hp\Desktop\solr-5.0.0\bin 下的solr.i ...
- [转]Selenium-Webdriver系列Python版教程(1)————快速开始
elenium的历史,selenium2与WebDriver的关系本文就不讲了,想了解的同学们百度一下就可以Ok. 本系列教程是以Selenium-WebDriver的Python版本,首先从 ...