简单的socket同一局域网之间通信

socket服务器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace socket
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        Socket ServerSocket = null;

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            //将IP地址和端口号绑定到网络节点point上  
            IPEndPoint IPE = new IPEndPoint(IPAddress.Parse(tboxIP.Text), Int32.Parse(tboxPort.Text));
            //实例化套接字
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定端口
            ServerSocket.Bind(IPE);
            //SOCket开始倾听
            ServerSocket.Listen(10);
            showmsg("服务器已启动,监听中...");

            //创建线程
            Thread thread = new Thread(ListenClientConnect);
            //后台线程
            thread.IsBackground=true;
            //线程开始
            thread.Start();

        }
        //创建一个字典集合
        Dictionary<string, Socket> dic = new Dictionary<string, Socket>();
        private void ListenClientConnect(object obj)
        {
            while (true)
            {
                //接收来自客户端信息
                Socket socketClient = ServerSocket.Accept();
                //把客户端IP装换为字符串
                string RemoteIP = socketClient.RemoteEndPoint.ToString();
                //字典集合添加IP
                dic.Add(RemoteIP, socketClient);
                //委托添加IP
                Dispatcher.Invoke(()=>lstboxIP.Items.Add(RemoteIP));
                showmsg(RemoteIP + "已连接");

                //创建接受信息线程
                Thread recieveThread = new Thread(recievemsg);
                //线程为后台线程
                recieveThread.IsBackground = true;
                //接收信息线程开始
                recieveThread.Start(socketClient);
            }
        }

        private void recievemsg(object soc)
        {

            Socket socketClient = (Socket)soc;

            while (true)
            {
                //byte数组  缓存区
                byte[] buffer = new byte[1024];
                //byte转int
                int n = socketClient.Receive(buffer);
               // string msg = Encoding.Default.GetString(buffer, 0, n);
                //以UTF8格式接收
                //string msg = Encoding.UTF8.GetString(buffer, 0, n);

                string msg = Encoding.Default.GetString(buffer, 0, n);
                //显示接收到的信息
                showmsg(socketClient.RemoteEndPoint.ToString()+":"+msg);
            }
        }

        private void showmsg(string p)
        {
            //换行加控件显示
            Dispatcher.BeginInvoke(new Action(() =>
                {
                    rtbx.AppendText(p + "\r\n");
                }));
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            //关闭socket
            ServerSocket.Close();
        }
        //发送信息
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {

            showmsg(tboxMsg.Text);
            //选中IP
            string ip = lstboxIP.SelectedValue.ToString();
            //以byte数组形式发送
            byte[] by = Encoding.UTF8.GetBytes(tboxMsg.Text);
            //发送信息
            dic[ip].Send(by,0);
            tboxMsg.Text = "";
        }
    }
}

界面代码

<Window x:Class="socket.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label x:Name="label" Content="IP地址:" HorizontalAlignment="Left" Margin="24,15,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tboxIP" HorizontalAlignment="Left" Height="23" Margin="86,17,0,0" TextWrapping="Wrap" Text="172.16.3.3" VerticalAlignment="Top" Width="92"/>
        <Label x:Name="label1" Content="端口:" HorizontalAlignment="Left" Margin="183,16,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tboxPort" HorizontalAlignment="Left" Height="23" Margin="228,17,0,0" TextWrapping="Wrap" Text="8488" VerticalAlignment="Top" Width="43"/>
        <Button x:Name="btnStart" Content="服务器启动" HorizontalAlignment="Left" Margin="287,19,0,0" VerticalAlignment="Top" Width="75" Click="btnStart_Click"/>
        <Button x:Name="btnStop" Content="服务器停止" HorizontalAlignment="Left" Margin="377,19,0,0" VerticalAlignment="Top" Width="75" Click="btnStop_Click"/>
        <ListBox x:Name="lstboxIP" HorizontalAlignment="Left" Height="180" Margin="377,65,0,0" VerticalAlignment="Top" Width="116"/>
        <Button x:Name="btnSend" Content="发送信息" HorizontalAlignment="Left" Margin="377,271,0,0" VerticalAlignment="Top" Width="75" Click="btnSend_Click"/>
        
        <TextBox x:Name="tboxMsg" HorizontalAlignment="Left" Height="23" Margin="24,270,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="320"/>
        <RichTextBox x:Name="rtbx" HorizontalAlignment="Left" Height="180" Margin="24,65,0,0" VerticalAlignment="Top" Width="320">
            <FlowDocument>
                <Paragraph>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>

    </Grid>
</Window>

socket客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace socket客户端
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        //客户端套接字
        Socket socketclient = null;
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(tboxIP.Text),Int32.Parse(tboxPort.Text));
            socketclient = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            socketclient.Connect(ipe);
            Showmsg("连接成功");

            //接受信息
            Thread th = new Thread(recievemsg);
            th.IsBackground = true;
            th.Start();
        }

        private void recievemsg(object obj)
        {
            while (true)
            {
                //缓冲字节
                byte[] by = new byte[1024];
                int n = socketclient.Receive(by);
                string msg = Encoding.Default.GetString(by, 0, n);
                Showmsg(socketclient.RemoteEndPoint.ToString() + ":" + msg);
            }
        }

        private void Showmsg(string p)
        {
            Dispatcher.Invoke(()=>rtboxInfo.AppendText(p+"\r\n"));
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            byte[] buffer = new byte[1024];
            Showmsg("我说"+tboxMsg.Text);
            buffer=Encoding.Default.GetBytes(tboxMsg.Text);
            socketclient.Send(buffer,0);
        }
    }
}

界面代码

<Window x:Class="socket客户端.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label x:Name="label" Content="IP地址:" HorizontalAlignment="Left" Margin="31,16,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tboxIP" HorizontalAlignment="Left" Height="23" Margin="86,17,0,0" TextWrapping="Wrap" Text="172.16.3.3" VerticalAlignment="Top" Width="92"/>
        <Label x:Name="label1" Content="端口:" HorizontalAlignment="Left" Margin="183,16,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tboxPort" HorizontalAlignment="Left" Height="23" Margin="228,17,0,0" TextWrapping="Wrap" Text="8488" VerticalAlignment="Top" Width="43"/>
        <Button x:Name="btnStart" Content="连接服务器" HorizontalAlignment="Left" Margin="287,19,0,0" VerticalAlignment="Top" Width="75" Click="btnStart_Click"/>
        <Button x:Name="btnSend" Content="发送信息" HorizontalAlignment="Left" Margin="379,260,0,0" VerticalAlignment="Top" Width="75" Click="btnSend_Click"/>
        <RichTextBox x:Name="rtboxInfo" HorizontalAlignment="Left" Height="180" Margin="41,65,0,0" VerticalAlignment="Top" Width="320">
            <FlowDocument>
                <Paragraph/>
            </FlowDocument>
        </RichTextBox>
        <TextBox x:Name="tboxMsg" HorizontalAlignment="Left" Height="23" Margin="41,260,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="321"/>
    </Grid>
</Window>
说明一下ip为本机ip地址,服务器发送信息,必须选择客户端发送
发布了3 篇原创文章 · 获赞 2 · 访问量 3103
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览