我是靠谱客的博主 体贴乌冬面,最近开发中收集的这篇文章主要介绍c# 使用TcpClient TcpListener类 服务器和客户端实现双向连接 web service web socket,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在这里插入图片描述

通过web service获取服务器ip地址 端口先写5000

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Services;

namespace WebApplication1
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
         [WebMethod(Description = "获取服务器ip地址 端口")]
        public string GetIP()
        {
            string AddressIP = string.Empty;
            //Dns.GetHostEntry(Dns.GetHostName()).AddressList
            foreach (IPAddress _IPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return JsonConvert.SerializeObject(new { state = true, IP = AddressIP,Port="5000" });
        }
    }
}

服务器

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;

namespace TCPServer
{
    public partial class TCPServer : Form
    {
        public TCPServer()
        {
            InitializeComponent();
        }

        //tcp监听
        private TcpListener listener;
        private TcpClient client;
        public BinaryReader br;
        public BinaryWriter bw;
        private void button1_Click(object sender, EventArgs e)
        {
            //获取本地ip并设置
            GetIP();
            textBox4.Text = "5000";
            Thread t = new Thread(server);
            t.IsBackground = true;
            t.Start(listener);

        }

        private void server(object o)
        {
            
            //服务端监听来自端口号5000 ip地址任意的信息   负责接收客户端连接请求(但不负责与客户端通信)的socket
            //listener = new TcpListener(IPAddress.Any, 5000);
            listener = new TcpListener(IPAddress.Parse(textBox3.Text), int.Parse(textBox4.Text));
            listener.Start();
            ShowMsg("服务器开始监听");
            client = listener.AcceptTcpClient();
            label.Text = "连接成功";
            ShowMsg(client.Client.RemoteEndPoint.ToString()+"连接成功");

            while (true)
            {
                try
                {
                    NetworkStream strem = client.GetStream();
                    br = new BinaryReader(strem);
                    string receive = null;
                    receive = br.ReadString();//读取
                    ShowMsg(client.Client.RemoteEndPoint.ToString() + ":" + receive);
                    
                }
                catch (Exception)
                {
                    MessageBox.Show("接收失败");
                }
                
            }


        }

        private void GetIP()
        {
            string ipc = "";
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                //Console.WriteLine(_IPAddress);
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }

            }
            ipc = AddressIP;
            textBox3.Text = ipc;


        }


        private void button3_Click(object sender, EventArgs e)
        {
            //利用TcpClient对象GetStream方法得到网络流
            NetworkStream clientStream = client.GetStream();
            bw = new BinaryWriter(clientStream);
            //写入
            bw.Write(textBox2.Text);
            ShowMsg("发送:" + textBox2.Text);

        }

        private void ShowMsg(string v)
        {
            textBox1.AppendText(v + "rn");
        }


        private void TCPServer_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}

客户端

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TCPServer
{
    public partial class TcpClient : Form
    {
        public TcpClient()
        {
            InitializeComponent();
        }

        
        private System.Net.Sockets.TcpClient client;
        public BinaryReader br;
        public BinaryWriter bw;
        //private string str;
        //连接
        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(clientA);
            t.IsBackground = true;
            t.Start();

        }


        private void button2_Click(object sender, EventArgs e)
        {
            WebReference.WebService1 ws = new WebReference.WebService1();
            var str = JsonConvert.DeserializeAnonymousType(ws.GetIP(),new { ip=string.Empty ,port= string.Empty });
            textBox3.Text = str.ip;
            textBox4.Text = str.port;

        }
        private void clientA()  
        {
            //通过服务器的ip和端口号,创建TcpClient实例
            client = new System.Net.Sockets.TcpClient();
            //使用指定的IP地址和端口号将客户端连接到TCP主机
            client.Connect(IPAddress.Parse(textBox3.Text), int.Parse(textBox4.Text));
            label.Text = "与服务器连接成功";
            ShowMsg("服务器:"+ client.Client.RemoteEndPoint.ToString());
            ShowMsg("客户端:" + client.Client.LocalEndPoint.ToString());
            while (true)
            {
                try
                {
                    NetworkStream clientStream = client.GetStream();
                    br = new BinaryReader(clientStream);
                    string receive = null;
                    receive = br.ReadString();
                    ShowMsg(client.Client.RemoteEndPoint.ToString() +":"+ receive);
                }
                catch
                {
                    MessageBox.Show("接收失败!");
                }
            }


        }

        
        private void button3_Click(object sender, EventArgs e)
        {

            NetworkStream clientStream = client.GetStream();
            bw = new BinaryWriter(clientStream);
            bw.Write(textBox2.Text);
            ShowMsg("发送:"+textBox2.Text);


        }
        
        private void ShowMsg(string v)
        {
            textBox1.AppendText(v + "rn");
        }
        private void TcpClient_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

       
    }
}

示例:

在这里插入图片描述
在这里插入图片描述

最后

以上就是体贴乌冬面为你收集整理的c# 使用TcpClient TcpListener类 服务器和客户端实现双向连接 web service web socket的全部内容,希望文章能够帮你解决c# 使用TcpClient TcpListener类 服务器和客户端实现双向连接 web service web socket所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部