Socket代码
服务器端
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代码的更多相关文章
- Netty实现的一个异步Socket代码
本人写的一个使用Netty实现的一个异步Socket代码 package test.core.nio; import com.google.common.util.concurrent.ThreadF ...
- SSL握手通信详解及linux下c/c++ SSL Socket代码举例
SSL握手通信详解及linux下c/c++ SSL Socket代码举例 摘自:http://www.169it.com/article/3215130236.html 分享到:8 发布时 ...
- SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码)
SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码) 摘自: https://blog.csdn.net/sjin_1314/article/det ...
- 网络编程之Socket代码实例
网络编程之Socket代码实例 一.基本Socket例子 Server端: # Echo server program import socket HOST = '' # Symbolic name ...
- 简单的 socket 代码
TCP 编程 客户端代码 将键盘输入的字符发送到服务端,并将从服务端接收到的字符输出到终端 #!/usr/python3 import socket def socket_client(): s = ...
- socket 代码实例
1. TCP SOCKET 客户端: #!/usr/bin/env python # -*-coding:utf-8 -*- import socket HOST = 'localhost' PO ...
- python入门之socket代码练习
Part.1 简单的socket单次数据传输 服务端: #服务器端 import socket server = socket.socket() # 声明socket类型,同时生成socket连接对象 ...
- 完整的Socket代码
先上图 列举一个通信协议 网关发送环境数据 此网关设备所对应的所有传感器参数,格式如下: 网关发送: 包长度+KEY值+请求类型+发送者+接收者+消息类型+消息内容 说明: 包长度:short int ...
- Python全栈开发:socket代码实例
客户端与服务端交互的基本流程 服务端server #!/usr/bin/env python # -*- coding;utf-8 -*- import socket sk = socket.sock ...
随机推荐
- Spring -- spring 中使用jdbc, c3p0连接池, dao概念
1. 示例代码 CustomerDao.java ,dao接口 public interface CustomerDao { public void insertCustomer(Customer ...
- LeetCode 之 TwoSum
题目: Given an array of integers, find two numbers such that they add up to a specific target number. ...
- LeetCode第[53]题(Java):Maximum Subarray
题目:和最大的子序列 难度:Medium 题目内容: Given an integer array nums, find the contiguous subarray (containing at ...
- CSS 实现隐藏滚动条同时又可以滚动(转)
CSS 实现隐藏滚动条同时又可以滚动 移动端页面为了更接近原生的体验,是否可以隐藏滚动条,同时又保证页面可以滚动? 使用 overflow:hidden 隐藏滚动条,但存在的问题是:页面或元素失去了滚 ...
- 用 LoadLibraryExW 函数测试加载 dll (CSharp、Windows)
效果如下: $ llbtest "E:\Developer\emgucv-windesktop 3.3.0.2824\libs\x64" LoadLibraryExW PATH: ...
- 小米手机调试出现DELETE_FAILED_INTERNAL_ERROR Error while Installing APKs
小米手机就是这样子,权限什么的总是做的比较严格,去开发者选项里面找答案,看了下很多都是以前的,在最底下发现了一个选项“启用MIUI优化”,其实一般手机的开发者选项里面是不会有这个选项的.关掉该选项,重 ...
- iOS自动化探索(四)自动化测试框架pytest - 安装和使用
自动化测试框架 - pytest pytest是Python最流行的单元测试框架之一, 帮助更便捷的编写测试脚本, 并支持多种功能复杂的测试场景, 能用来做app测试也能用作函数测试 官方文档: ht ...
- 内存保护机制及绕过方案——通过覆盖SEH异常处理函数绕过/GS机制
通过SEH链绕过GS保护机制 ⑴. 原理分析: i.异常处理结构(SEH)处理流程如下: SEH是基于线程的,每一个线程都有一个独立的SEH处理结果,在线程信息块中的第一个结构指向线程的异常列表,F ...
- SpringCloud教程 | 第七篇: 高可用的分布式配置中心(Spring Cloud Config)
版权声明:本文为博主原创文章,欢迎转载,转载请注明作者.原文超链接 ,博主地址:http://blog.csdn.net/forezp. http://blog.csdn.net/forezp/art ...
- Struts2 用过滤器代替了 servlet ,???? 且不需要tomcat就可以直接做功能测试
Struts2 用过滤器代替了 servlet ,???? 且不需要tomcat就可以直接做功能测试