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"), 3001));   //这里要写客户端访问的地址
            server.Listen(10);
            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"), 3001));
            server.Listen(10);
            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, 0, 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 > 0)
            {
                box.Bulider.Append(Encoding.ASCII.GetString(box.Bytes, 0, byteread));

                content = box.Bulider.ToString();

                if (content.IndexOf("") > -1)
                {
                    Send(handler, "ok");
                }
                else
                {
                    handler.BeginReceive(box.Bytes, 0, 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, 0, byteData.Length, 0,
                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"), 3001);
                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, 3001);

            }
            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, 0, 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 > 0)
            {
                box.Builder.Append(Encoding.ASCII.GetString(box.Bytes, 0, length));

                content = box.Builder.ToString();

                if (content.IndexOf("") > -1)
                {
                    MessageBox.Show(content);
                    client.Close();
                }
                else
                {
                    client.BeginReceive(box.Bytes, 0, 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[1024];

            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)
        {

        }
    }
}

Socket代码

时间: 2024-10-07 13:12:45

Socket代码的相关文章

入门级的Java Socket代码

在男友手把手的指导下,写出第一个类似于"hello world"的socket程序. 男友要求: 1. 程序以命令行方式运行,在两台联网的电脑上分别运行: 2. 一台电脑的命令行中输入"程序名称 wait",运行程序,进入监听状态: 3. 一台电脑的命令行中输入"程序名称 ip地址",运行程序,连接另一台电脑: 4. 两台电脑均可发送接收消息. 分析流程图: 附代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1

Python--网络编程-----socket代码实例

一.基本socket例子 服务端: 1 import socket 2 3 HOST = '' 4 PORT = 50007 5 6 sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 sock_server.bind((HOST, PORT)) 8 9 sock_server.listen(1) 10 conn, addr = sock_server.accept() 11 12 with conn: 13 pri

Python--网络编程-----socket代码实例--聊天软件升级版

服务端代码: 1 import socket 2 3 HOST = '' 4 PORT = 50007 5 6 sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 sock_server.bind((HOST, PORT)) 8 9 sock_server.listen(1) 10 11 while True: 12 conn, addr = sock_server.accept() 13 14 with conn:

4 Socket代码实例

基本Socket例子 做了这么久的铺垫,是时候该与远方的她say hi啦 Server # Echo server program import socket HOST = '' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) so

Linux 网络编程三(socket代码详解)

//网络编程客户端 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h>//htons()函数头文件 #include <ne

php socket 客户端代码

<?php class SendDevAction{ //log日志文件 private $logDevFile = ""; //日志字符串 private $logStr = ""; //用于发送接收的socket对象 private $socket; //socket连接对象 private $connect; //对方服务器ip private $host = "211.155.82.229"; //服务器端口 private $po

c# socket select 模型代码(u3d)

其实写过多次网络链接.但是因为换了工作,又没电脑在身边,所以以前的代码都没办法翻出来用. 所以从今天起,一些常用的代码只好放到网上. 公司有一个局域网的游戏.本来想用u3d的rpc就可以完成.但是后来说要传语音.于是只要写一个tcp. 先给出服务器和客户端的socket代码段.其他依赖的一些文件,就不贴了. 目前完成的模块大的说就两块,网络和消息分发. 网络部分服务器有玩家池的管理. 网络部分没有想得很详细.因为是局域网,所以也不存在多大开销.如果有需要上千的需求,可能还要优化下代码结构以及锁.

C#版 Socket编程(最简单的Socket通信功能)

原文://http://blog.csdn.net/linybo/article/details/51141960 示例程序是同步套接字程序,功能很简单,只是客户端发给服务器一条信息,服务器向客户端返回一条信息:这里只是一个简单的示例,是一个最基本的socket编程流程,在接下来的文章中,会依次记录套接字的同步和异步,以及它们的区别. 第一步:用指定的端口号和服务器的ip建立一个EndPoint对像: 第二步:建立一个Socket对像: 第三步:用socket对像的Bind()方法绑定EndPo

socket入门

对于一个初学者来说,写代码是痛苦的,写不会的代码更痛苦,然后对于网上残次不齐的源码,blog不懂怎么实现痛上加痛. 本文仅仅站在入门基础上写SOCKET代码,并且代码非原创. 1.怎么建工程 VS编译器:文件->新建->项目; 大概是这样. 然后是名称随便,然后下一步,完成. 大概是这样. 注意那个 #include “stdafx.h" 基本上 你用win32控制台写代码都需要这个头文件. 代码引用这个博客:http://blog.csdn.net/orange_xxx/artic