服务器端

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. Hibernate -- 一对一映射

    一对一关联指两个表之间的记录是一一对应的关系.分为两种:外键关联和主键关联. (1)外键关联 比如一家公司(Company)和它所在的地址(Address).在业务逻辑中要求一家公司只有唯一的地址,一 ...

  2. 求中位数,O(n)的java实现【利用快速排序折半查找中位数】

    查找无序数组的中位数,要想时间复杂度为O(n)其实用计数排序就能很方便地实现,在此讨论使用快速排序进行定位的方法. 1.中位数定义 2.算法思想 3.Java代码实现 4.时间复杂度分析 5.附录 中 ...

  3. Pycharm for mac 快捷键

    cmd b 跳转到声明处(cmd加鼠标) opt + 空格 显示符号代码 (esc退出窗口 回车进入代码) cmd []光标之前/后的位置 opt + F7 find usage cmd backsp ...

  4. vue开发者工具DejaVue

    刚刚在逛github的时候发现了一个vue开发工具觉得很不错,分享给v友们! 地址:https://github.com/MiCottOn/DejaVue 话不多说,直接说操作流程!(前提是node版 ...

  5. datagrid中用tooltip

    function msgFormat(value,row){ value = value.replace(/ /g," "); return '<span title='+ ...

  6. Ceph:pg peering过程分析

    转自:https://www.ustack.com/blog/ceph%ef%bc%8dpg-peering/ Peering:互为副本的三个(此处为设置的副本个数,通常设置为3)pg的元数据达到一致 ...

  7. winform 中 MessageBox 用法大全

    (转自:http://blog.csdn.net/xuenzhen123/article/details/4808005) MessageBox.Show()共有21中重载方法.现将其常见用法总结如下 ...

  8. linux/unix shell bash script 小记

    #script PSAATL11*` do $i | awk -F ':' '{print $1}'` do ((k=j+)); m=$(zcat $i | sed -n ${j},${k}p); e ...

  9. Spring 自动装配;方法注入

    通过配置defalut—autowire属性,Spring IOC容器可以自动为程序注入Bean:默认是no(不启用自动装配). default—autowire的类型有: byName:通过名称自动 ...

  10. 条款23:宁以non-member, non-friend,替换member函数。

    考虑下面这种经常出现的使用方式: class webBroswer{ public: ... void clearCache(); void clearHistory(); void removeCo ...