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
{
    /// 
    /// WebService1 的摘要说明
    /// 
    [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 + "\r\n");
        }


        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 + "\r\n");
        }
        private void TcpClient_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

       
    }
}

示例:

c# 使用TcpClient TcpListener类 服务器和客户端实现双向连接 web service web socket_第1张图片
c# 使用TcpClient TcpListener类 服务器和客户端实现双向连接 web service web socket_第2张图片

你可能感兴趣的:(socket,c#,.net)