socket  socket讲解

一.socket是何物?

参考百度百科:

http://baike.baidu.com/link?url=4YNURsJLEaL0II79C68gPUoYKliXWJLM8V6H5QL0r_QOEmrxSQsnFPYxeuBx1U1bukTcAxhcl1glTOjxiGZBgSqb5G9_4N9Dj-XX-jXtXba

二.socket常用类及函数讲解:(为如下demo做准备)

IPAddress:

IPAddress.Parse();

IPEndPoint:

Encoding:

Encoding.Unicode.GetString()
Encoding.Unicode.GetBytes()

Socket:

Send、Receive、Accept;

Thread:

Thread.Sleep();

三.Demo:(仅供参考)

1.Client  code:

 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.Sockets;
using System.Net;
using System.Threading; namespace ClientSocket_Demo
{
public partial class Client : Form
{
public Client()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
} private Socket connSocket;
private Thread ReceiveThread; private void btnConnection_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtIp.Text))
{
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "ip is null");
return;
}
if (string.IsNullOrEmpty(txtPort.Text))
{
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "port is null");
return;
}
Connection();
} private void btnSend_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtMsg.Text))
{
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "msg is null");
return;
}
SendMsg();
} /// <summary>
/// connection
/// </summary>
private void Connection()
{
IPAddress ip = IPAddress.Parse(txtIp.Text);
IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(txtPort.Text));
connSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
connSocket.Connect(endPoint);
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "connection success.");
btnConnection.Enabled = false; }
catch (Exception ex)
{
connSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "connection fail.");
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString());
} ReceiveThread = new Thread(ReceiveCallBack);
ReceiveThread.Start();
ReceiveThread.IsBackground = true;
} /// <summary>
/// send msg
/// </summary>
private void SendMsg()
{
byte[] buffer = new byte[];
string msg = txtMsg.Text;
lstLog.Items.Add(DateTime.Now.ToString() + ":" + msg);
buffer = Encoding.Unicode.GetBytes(msg); if (connSocket != null)
{
connSocket.Send(buffer);
}
else
{
connSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "send fail.");
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "no connection!");
}
} /// <summary>
/// receive
/// </summary>
private void ReceiveCallBack()
{
byte[] buffer = new byte[];
int count = ; while (true)
{
Thread.Sleep();
try
{
count = connSocket.Receive(buffer);
if (count == )
{
connSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":server disconnect.");
break;
}
string msg = Encoding.Unicode.GetString(buffer,, count);
lstLog.Items.Add(DateTime.Now.ToString() + ":" + msg);
}
catch (Exception ex)
{
connSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":server disconnect.");
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString());
break;
}
}
}
}
}

2.Server code:

 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.Windows.Forms; namespace Socket_Demo
{
public partial class Server : Form
{
public Server()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
} private Socket connSocket;
private Thread listenThread;
private Thread ReceiveThread; private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtIp.Text))
{
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "ip is null");
return;
}
if (string.IsNullOrEmpty(txtPort.Text))
{
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "port is null");
return;
}
Start();
} /// <summary>
/// start
/// </summary>
private void Start()
{
byte[] buffer = new byte[];
IPAddress ip = IPAddress.Parse(txtIp.Text);
IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(txtPort.Text));
connSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connSocket.Bind(endPoint);
connSocket.Listen();
lstLog.Items.Add(DateTime.Now.ToString() + ":" + "listen:" + txtPort.Text);
button1.Enabled = false; //监听线程
listenThread = new Thread(ListenCallBack);
listenThread.Start(connSocket);
listenThread.IsBackground = true;
} /// <summary>
/// listen
/// </summary>
/// <param name="o"></param>
private void ListenCallBack(object obj)
{
string ip = string.Empty; //创建监听套接字
Socket listenSocket = obj as Socket; while (true)
{
Thread.Sleep(); try
{
//创建通信套接字
Socket socket = listenSocket.Accept();
ip = socket.RemoteEndPoint.ToString();
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ip + " connect success."); //通信线程
ReceiveThread = new Thread(ReceiveCallBack);
ReceiveThread.Start(socket);
ReceiveThread.IsBackground = true;
}
catch (Exception ex)
{
listenSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString());
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ip + " connect fail.");
break;
}
}
} /// <summary>
/// receive
/// </summary>
/// <param name="o"></param>
private void ReceiveCallBack(object o)
{
byte[] buffer = new byte[];
int count = ;
string ip = string.Empty; Socket ReceiveSocket = o as Socket; while (true)
{
Thread.Sleep();
try
{
ip = ReceiveSocket.RemoteEndPoint.ToString();
count = ReceiveSocket.Receive(buffer);
if (count == )
{
ReceiveSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":client disconnect.");
break;
}
string msg = Encoding.Unicode.GetString(buffer, , count);
lstLog.Items.Add(DateTime.Now.ToString() + ":" + msg);
}
catch (Exception ex)
{
ReceiveSocket.Close();
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ip + "client disconnect.");
lstLog.Items.Add(DateTime.Now.ToString() + ":" + ex.ToString());
break;
}
}
} private void Server_Load(object sender, EventArgs e)
{
var localhostIp = Dns.GetHostEntry(Dns.GetHostName()).AddressList[];
txtIp.Text = localhostIp.ToString();
txtPort.Text = "";
}
}
}

四.注意事项:

socket socket讲解的更多相关文章

  1. [Socket]Socket文件传输

    1.Server import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException ...

  2. [Socket]Socket聊天小程序

    一个简单是Socket聊天小程序,读写操作在不同的线程中.服务器端采用线程池. 1.Server import java.io.IOException; import java.net.ServerS ...

  3. [Socket]Socket进程间的通信

    转自:http://blog.csdn.net/giantpoplar/article/details/47657303 前面说到的进程间的通信,所通信的进程都是在同一台计算机上的,而使用socket ...

  4. ResourceWarning: unclosed <socket.socket fd=864, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('10.100.x.x', 37321), raddr=('10.1.x.x', 8500)>解决办法

    将代码封装,并使用unittest调用时,返回如下警告: C:\python3.6\lib\collections\__init__.py:431: ResourceWarning: unclosed ...

  5. Python socket & socket server

    socket 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket(套接字). 建立网络通信连接至少要一对socket.socket是对TCP/IP的封装 使用方法 ...

  6. 关于iOS socket的讲解介绍

    socket(套接字)是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元,包含进行网络通信必须的五种信息:连接使用的协议,本地主机的IP地址,本地进程的协议端口,远地主机的IP地址,远地进程 ...

  7. dotnet调用node.js写的socket服务(websocket/socket/socket.io)

    https://github.com/jstott/socketio4net/tree/develop socket.io服务端node.js,.里面有js写的客户端:http://socket.io ...

  8. socket系列之客户端socket——Socket类

    假设TCP套接字服务器端已经建立好并正在监听客户端的连接了,那么客户端就可以通过Socket类来发起连接.客户端发起一个连接请求后,就被动地在等待服务器的响应.这个类同样位于java.net包中,包含 ...

  9. 执行Socket socket = new Socket(ip, port);时抛出个异常:android.os.NetworkOnMainThreadException解决办法

    首先,确认你的android版本是4.0之后再用此方法解决,因为在4.0之后在主线程里面执行Http请求才会报这个错,也许是怕Http请求时间太长造成程序假死的情况吧.Android在4.0之前的版本 ...

随机推荐

  1. Ubuntu 16.04 LTS制作本地源

    平时apt-get install安装软件时,下载的deb文件都会存放在/var/cache/apt/archives/下,没有网络时就需要将这些deb制作成本地源.另外,如果在本机架一个简单的网络服 ...

  2. php system()

    学习源头: https://blog.csdn.net/ltx06/article/details/53992905 system(“nohup ./test.py $s &”); 这个不会在 ...

  3. MD5加密 及获得密码盐

    MD5加密 及获得密码盐 using System; using System.Collections.Generic; using System.Configuration; using Syste ...

  4. HP 防止cciss设备被DM映射

    http://h10025.www1.hp.com/ewfrf/wc/document?cc=cn&lc=zh-hans&dlc=zh-hans&docname=c034933 ...

  5. python第二十三天-----Tornado

    Tornado是一个轻量级完整的web框架,在Linux系统下它会使用epoll,是一个异步非阻塞的web服务器框架,对于实时应用来说很理想,想想同是异步非阻塞的nginx的残暴程度就知道了 1.路由 ...

  6. appium-unittest框架中的断言

    1.首先unittest本身是一个python的测试框架,他有他自己的使用规则: 2.如果用其中的方法,需要引入,方法: import unittest class Login(unittest.Te ...

  7. Python多进程-进程间数据的传递

    两个进程间的数据是独立的,要进行数据传递的话可通过几个方法 Queue 通过队列来进行进程间数据的传递 # -*- coding:utf-8 -*- __author__ = "MuT6 S ...

  8. CentOS 7.2 部署Rsync + Lsyncd服务实现文件实时同步/备份 (二)

    发送端配置: 一.配置密钥 1. 主/从服务器之间启用基于密钥的身份验证.登录发送端服务器并用 " ssh-keygen " 命令生成公共或私有的密钥. 2. 使用 " ...

  9. leetcode860

    使用C++进行编码: bool lemonadeChange(vector<int>& bills) { ; ; ; int N = bills.size(); ; i < ...

  10. spring中的class配置不能使用properties中的字符串

    1.比如在a.properties中我们声明了一个变量: classRoom=com.wc82.ClassRoom 2.然后在spring的配置文件中:applicationContext.xml,有 ...