服务器端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace DMServer
{
public partial class Form1 : Form
{
Thread TempThread;
Socket server; string labelText = string.Empty; public string LabelText
{
get { return labelText; }
set
{
labelText = value;
}
} public static ManualResetEvent allDone = new ManualResetEvent(false); bool isDo = false; public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } /// <summary>
/// 用这个方法,另一个经测试是不好使的
/// </summary>
public void StartReceive()
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool isGo = true;
server.Bind(new IPEndPoint(IPAddress.Parse("192.168.10.128"), )); //这里要写客户端访问的地址
server.Listen();
Box box = new Box();
while (isGo)
{
try
{
Socket s = server.Accept();
string content = string.Empty;
byte[] bs = new byte[s.Available]; int num = s.Receive(bs); content += Encoding.ASCII.GetString(bs); s.Send(Encoding.ASCII.GetBytes("ok"));
if (content.Equals("ABCD123"))
{
isGo = false;
}
}
catch (Exception ex)
{ } } server.Close();
} /// <summary>
/// 不好使
/// </summary>
public void StartReceive1()
{
server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ));
server.Listen();
Box box = new Box();
box.WorkSocket = server;
while (true)
{
allDone.Reset();
server.BeginAccept(new AsyncCallback(ConnClient), box);
allDone.WaitOne();
}
} public void ConnClient(IAsyncResult ar)
{
Socket socket = ((Box)ar.AsyncState).WorkSocket;
Socket client = socket.EndAccept(ar); Box box = new Box();
box.WorkSocket = client; client.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
} public void Receive(IAsyncResult ar)
{
string content = string.Empty; Box box = (Box)ar.AsyncState; Socket handler = box.WorkSocket; int byteread = handler.EndReceive(ar); if (byteread > )
{
box.Bulider.Append(Encoding.ASCII.GetString(box.Bytes, , byteread)); content = box.Bulider.ToString(); if (content.IndexOf("") > -)
{
Send(handler, "ok");
}
else
{
handler.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
}
}
} private static void Send(Socket handler, String data)
{
// 消息格式转换.
byte[] byteData = Encoding.ASCII.GetBytes(data); // 开始发送数据给远程目标.
handler.BeginSend(byteData, , byteData.Length, ,
new AsyncCallback(SendCallback), handler);
} private static void SendCallback(IAsyncResult ar)
{ // 从state对象获取socket.
Socket handler = (Socket)ar.AsyncState; //完成数据发送
int bytesSent = handler.EndSend(ar); handler.Shutdown(SocketShutdown.Both);
handler.Close();
} private void button2_Click(object sender, EventArgs e)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(IPAddress.Parse("192.168.10.128"), );
socket.Send(Encoding.ASCII.GetBytes("ABCD123"));
}
catch (Exception ex)
{ }
socket.Close();
} private void button1_Click(object sender, EventArgs e)
{
TempThread = new Thread(new ThreadStart(StartReceive));
TempThread.Start();
}
}
}

客户端

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; namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse("192.168.10.128"); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try
{
client.Connect(ip, ); }
catch (Exception ex)
{
MessageBox.Show("连接失败!");
return;
} try
{
client.Send(Encoding.ASCII.GetBytes(this.textBox1.Text));
}
catch (Exception)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
return;
} Box box = new Box(); box.WorkSocket = client; client.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
} public void Receive(IAsyncResult ar)
{
string content = string.Empty; Box box = (Box)ar.AsyncState; Socket client = box.WorkSocket; int length = client.EndReceive(ar); if (length > )
{
box.Builder.Append(Encoding.ASCII.GetString(box.Bytes, , length)); content = box.Builder.ToString(); if (content.IndexOf("") > -)
{
MessageBox.Show(content);
client.Close();
}
else
{
client.BeginReceive(box.Bytes, , box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
}
}
} public class Box
{
Socket workSocket; public Socket WorkSocket
{
get { return workSocket; }
set { workSocket = value; }
} byte[] bytes = new byte[]; public byte[] Bytes
{
get { return bytes; }
set { bytes = value; }
} StringBuilder builder = new StringBuilder(); public StringBuilder Builder
{
get { return builder; }
set { builder = value; }
}
} private void Form1_Load(object sender, EventArgs e)
{ }
}
}

实际应用服务器端的开启方法,注意进程休眠的位置是为了解决运行太快接受不到传过来的数据的问题:

public void Start(object port)
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool isGo = true;
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[];
server.Bind(new IPEndPoint(ip, int.Parse(port.ToString())));
server.Listen();
while (isGo)
{
try
{
s = server.Accept();
Thread.Sleep(); //这里要注意,服务器端休眠的时间一定要比客户端少,否则和客户端一样或者大会导致客户端接收不到数据,不休眠自己会接收不到数据。
s.SendTimeout = ;
string content = "";
byte[] bytes = new byte[s.Available];
int num = s.Receive(bytes, , bytes.Length, SocketFlags.None); content = Encoding.UTF8.GetString(bytes); if (content.Equals("conn"))
{
s.Send(Encoding.UTF8.GetBytes("Data Source=" + ip.ToString() + ";Initial Catalog=DM;Persist Security Info=True;User ID=dm;Password=dm"));
}
if (content.Equals("Close"))
{
isGo = false;
}
}
catch (Exception ex)
{ }
}
s.Close();
server.Close();
}

这是修改后的客户端接受代码:

private void button1_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse("192.168.10.128"); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try
{
client.Connect(ip, ); }
catch (Exception ex)
{
MessageBox.Show("连接失败!");
return;
} try
{
client.Send(Encoding.UTF8.GetBytes(this.textBox1.Text));
}
catch (Exception)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
return;
}
string content = string.Empty;
int num = ;
Thread.Sleep();
byte[] b = new byte[client.Available];
num = client.Receive(b, , b.Length, SocketFlags.None);
content = Encoding.UTF8.GetString(b);
MessageBox.Show(content);
client.Close();
client.Dispose();
}

Socket代码的更多相关文章

  1. Netty实现的一个异步Socket代码

    本人写的一个使用Netty实现的一个异步Socket代码 package test.core.nio; import com.google.common.util.concurrent.ThreadF ...

  2. SSL握手通信详解及linux下c/c++ SSL Socket代码举例

    SSL握手通信详解及linux下c/c++ SSL Socket代码举例 摘自:http://www.169it.com/article/3215130236.html   分享到:8     发布时 ...

  3. SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码)

    SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码) 摘自: https://blog.csdn.net/sjin_1314/article/det ...

  4. 网络编程之Socket代码实例

    网络编程之Socket代码实例 一.基本Socket例子 Server端: # Echo server program import socket HOST = '' # Symbolic name ...

  5. 简单的 socket 代码

    TCP 编程 客户端代码 将键盘输入的字符发送到服务端,并将从服务端接收到的字符输出到终端 #!/usr/python3 import socket def socket_client(): s = ...

  6. socket 代码实例

    ​ 1. TCP SOCKET 客户端: #!/usr/bin/env python # -*-coding:utf-8 -*- import socket HOST = 'localhost' PO ...

  7. python入门之socket代码练习

    Part.1 简单的socket单次数据传输 服务端: #服务器端 import socket server = socket.socket() # 声明socket类型,同时生成socket连接对象 ...

  8. 完整的Socket代码

    先上图 列举一个通信协议 网关发送环境数据 此网关设备所对应的所有传感器参数,格式如下: 网关发送: 包长度+KEY值+请求类型+发送者+接收者+消息类型+消息内容 说明: 包长度:short int ...

  9. Python全栈开发:socket代码实例

    客户端与服务端交互的基本流程 服务端server #!/usr/bin/env python # -*- coding;utf-8 -*- import socket sk = socket.sock ...

随机推荐

  1. B树, B-树,B+树,和B*树的区别

    B树: B树的搜索,从根结点开始,如果查询的关键字与结点的关键字相等,那么就命中: 否则,如果查询关键字比结点关键字小,就进入左儿子:如果比结点关键字大,就进入 右儿子:如果左儿子或右儿子的指针为空, ...

  2. 四十四 Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的基本查询

    1.elasticsearch(搜索引擎)的查询 elasticsearch是功能非常强大的搜索引擎,使用它的目的就是为了快速的查询到需要的数据 查询分类: 基本查询:使用elasticsearch内 ...

  3. zabbix原理

    数据采集-->数据存储-->数据展示和分析-->报警 数据采集 SNMP agent ICMP/ssh/IPMT数据存储: cacti:rrd nagios:无数据库.mysql z ...

  4. mysql 库与表操作

    1. 库操作 1.1. 创建数据库 语法规则:create database 库名; CREATE DATABASE dt55; 在创建库时,希望指定编码语法:create database 库名 c ...

  5. 【Java】对象的创建过程

    一.对象的创建过程 1.首次创建对象时或该类静态方法/静态域首次被访问时,JAVA解释器查找该类的路径,定位该类的class文件 2.载入该类的class文件,有关静态初始化的所有动作执行,但是只执行 ...

  6. 使用VS自带的工具分析.NET程序的性能

    (转自:http://www.cnblogs.com/DebugLZQ/archive/2012/07/10/2585245.html) 这篇博文给大家分享的是,如何使用VS自带的性能分析工具来分析我 ...

  7. 伪变量foo foober是什么意思

    原文: The terms foobar, foo, bar, baz and qux are sometimes used as placeholder names (also referred t ...

  8. android实现log日志输出

    1.下载android的log4j的库(的封装) 去: http://code.google.com/p/android-logging-log4j/ 下载对应的 android-logging-lo ...

  9. UI- Layer的使用总结(附动画)

    #pargma mark - Layer 1. 设置当前视图的背景颜色 self.view.backgroundColor = [UIColor lightGrayColor]; 2. 创建一个视图, ...

  10. 剑指offer--35.数组中只出现一次的数字

    时间限制:1秒 空间限制:32768K 热度指数:198150 本题知识点: 数组 题目描述 一个整型数组里除了两个数字之外,其他的数字都出现了两次.请写程序找出这两个只出现一次的数字. class ...