您的位置:首页 > 理论基础 > 计算机网络

[非技术参考]C# Socket网络编程

2015-01-04 16:13 387 查看
我们在讲解Socket编程前,先看几个和Socket编程紧密相关的概念:

1. TCP/IP层次模型

当然这里我们只讨论重要的四层

01,应用层(Application):应用层是个很广泛的概念,有一些基本相同的系统级TCP/IP应用以及应用协议,也有许多的企业应用和互联网应用。http协议在应用层运行。

02,传输层(Tanspot):传输层包括UDP和TCP,UDP几乎不对报文进行检查,而TCP提供传输保证。

03,网络层(Netwok):网络层协议由一系列协议组成,包括ICMP、IGMP、RIP、OSPF、IP(v4,v6)等。

04,链路层(Link):又称为物理数据网络接口层,负责报文传输。

然后我们来看下tcp层次模型图

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
//建立通信用的Socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

public Form1()
{
InitializeComponent();
}

private void btnConnect_Click(object sender, EventArgs e)
{
//连接到目的IP, IPAddress ip = IPAddress.Any;用于自动获取IP地址
IPAddress ip = IPAddress.Parse(txtIP.Text);

//连接到目标ip地址的哪个应用(端口号!)
IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));

try
{
//连接到服务器
clientSocket.Connect(point);
ShowMsg("连接成功");
ShowMsg("服务器" + clientSocket.RemoteEndPoint.ToString());
ShowMsg("客户端" + clientSocket.LocalEndPoint.ToString());

//连接成功后,就可以接收服务器的发送信息了
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start();
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}

}//btnConnect_Click()

/// <summary>
/// 接收服务器信息
/// </summary>
void ReceiveMsg()
{
while (true)
{
try
{
byte[] buffer = new byte[1024];
int n = clientSocket.Receive(buffer);

//Encoding这个类里有byte数组和字符串转换的函数
string str = Encoding.UTF8.GetString(buffer, 0, n);
ShowMsg(clientSocket.RemoteEndPoint.ToString() + ": " + str);
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}//while
}//ReceiveMsg()

/// <summary>
/// 显示信息
/// </summary>
/// <param name="Msg"></param>
void ShowMsg(string Msg)
{
txtLog.AppendText(Msg + "\r\n");
}

private void btnSend_Click(object sender, EventArgs e)
{
if(clientSocket != null)
{
try
{
//把发送窗口的数据显示到记录窗口
ShowMsg(txtMsg.Text);

//字符数组
byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
clientSocket.Send(buffer);
txtMsg.Text = "";
}
catch(Exception ex)
{
ShowMsg(ex.Message);
}
}
}//btnSend_Click()

private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
}
}


View Code
注意:Control.CheckForIllegalCrossThreadCalls = false;这句话要在formLoad事件中执行,不然会出现运行错误:线程间操作无效: 从不是创建控件“”的线程访问它。

因为线程操作了一个UI控件,但是这个UI控件不是该线程创建的,就会出错。

还有三个知识点:

Dictionary<TKey, TValue> 类表示键和值的集合。
命名空间:System.Collections.Generic
Dictionary<string, string>是一个泛型

他本身有集合的功能有时候可以把它看成数组

他的结构是这样的:Dictionary<[key], [value]>

他的特点是存入对象是需要与[key]值一一对应的存入该泛型

通过某一个一定的[key]去找到对应的值

举个例子:

//实例化对象

Dictionary<int, string> dic = new Dictionary<int, string>();

//对象打点添加

dic.Add(1, "one");

dic.Add(2, "two");

dic.Add(3, "one");

//提取元素的方法

string a = dic[1];

string b = dic[2];

string c = dic[3];

//1、2、3是键,分别对应“one”“two”“one”

//上面代码中分别把值赋给了a,b,c

//注意,键相当于找到对应值的唯一标识,所以不能重复

//但是值可以重复


Socket的一个属性RemoteEndPoint和LocalEndPoint:源代码中直接使用的是RemoteEndPoint.ToString()返回的格式是IP:Port。服务器字典里的key就是IP:Port形式的字符串。

Socket.RemoteEndPoint 属性,他是Socket类的一个属性。
定义为:public EndPoint RemoteEndPoint { get; }

如果您使用的是面向连接的协议,则 RemoteEndPoint 属性将获取包含 Socket 连接到的远程 IP 地址和端口号的 EndPoint。
而如果当前使用的是无连接的协议,则 RemoteEndPoint 包含将要和 Socket 通信的默认远程 IP 地址和端口号。
您必须将此 EndPoint 强制转换为 IPEndPoint 才能检索信息。 然后就可以调用 IPEndPoint.Address 方法来检索远程 IPAddress,调用 IPEndPoint.Port 方法来检索远程端口号。

s.Connect (lep);
// Using the RemoteEndPoint property.
Console.WriteLine ("I am connected to " + IPAddress.Parse (((IPEndPoint)s.RemoteEndPoint).Address.ToString ()) + "on port number " + ((IPEndPoint)s.RemoteEndPoint).Port.ToString ());
// Using the LocalEndPoint property.
Console.WriteLine ("My local IpAddress is :" + IPAddress.Parse (((IPEndPoint)s.LocalEndPoint).Address.ToString ()) + "I am connected on port number " + ((IPEndPoint)s.LocalEndPoint).Port.ToString ());


字符数组和字符串之间的转换:

Encoding.UTF8.GetString()
Encoding.UTF8.GetBytes()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐