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. ECMAScript6入门-序言

    本系列笔记基于阮一峰大佬的开源书籍.如果大家想看可以去该地址 本系列笔记只记录本人自己学习的过程,如果有侵权收到通知会自行下架. 如果大家看到可以直接去地址处学习,如果觉得好还望支持正版. 在此感谢阮 ...

  2. linux 定时备份mysql

    定时备份:1.创建备份文件存放目录2.创建备份脚本backup.sh #!/bin/bash DBUser=db_backDBPasswd=passwordDBName=db_nameSERVER=l ...

  3. jenkins插件

    构建maven项目:Maven Release Plug-in Plug-in

  4. 西安电子科技大学第16届程序设计竞赛 F Operating System (unique() 去重函数)

    链接:https://www.nowcoder.com/acm/contest/107/F来源:牛客网 Operating System 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ ...

  5. 1104 Sum of Number Segments

    题意: 给出n个不大于1.0的小数序列,如{ 0.1, 0.2, 0.3, 0.4 },则共有10个分片(0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, ...

  6. 10-17C#第四部分--类型(1)

    C#类型--String类 一.String类型 () 注:string与String的不同:string属于String的数据类型,小写string是大写String类型的实例化:string属于S ...

  7. Samba服务学习报错总结

    1 2 3 4 5 此文献来至百度文库 http://wenku.baidu.com/link?url=hkHembjXcjoYRU9ky34a46Lzv5SAEutwa0v1_F8INQsdg_KK ...

  8. IE6中浮动双边距bug

    想要创建出漂亮的网页设计, 除了要认真学习每一个html和CSS代码之外,不可能不去了解一下臭名昭著的IE6和更早的那些IE浏览器的坏脾气,因为你本来写出的规规矩矩的代码, 漂亮的设计就此就要完成了, ...

  9. php中用大括号把?>和<?php框起来的作用

    <?php function my_function() { ?> My function was called <!--就是这里,为什么前面要用?>和< ?php 把M ...

  10. 项目一:第十四天 1.在realm中动态授权 2.Shiro整合ehcache 缓存realm中授权信息 3.动态展示菜单数据 4.Quartz定时任务调度框架—Spring整合javamail发送邮件 5.基于poi实现分区导出

    1 Shiro整合ehCache缓存授权信息 当需要进行权限校验时候:四种方式url拦截.注解.页面标签.代码级别,当需要验证权限会调用realm中的授权方法   Shiro框架内部整合好缓存管理器, ...