Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
初出茅庐多多指教 2016-04-11 14:31 采纳率: 50%
浏览 4312

C#客户端为什么连接不上服务器,当ip地址为127.0.0.1是没有问题的

就是自己的电脑是连接路由器的,但是ip不是192.168.开头的,不知道是公网问题还是什么问题,测试都是用自己的一台电脑的。

  • 写回答

4条回答 默认 最新

  • 初出茅庐多多指教 2016-04-11 14:32
    关注

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

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

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
    
        }
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        Socket socketSend;
        private void btnStart_Click(object sender, EventArgs e)
        {
            try 
            {
                //当点击开始监听时,创建一个负责监听IP地址和端口号的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //创建ip对象
                IPAddress ip=IPAddress.Any;//IpAddress.Parse(txtServer.Text);
                //创建端口对象
                IPEndPoint point=new IPEndPoint(ip,Convert.ToInt32(txtPort.Text));
                //监听端口
                socketWatch.Bind(point);
                ShowMsg("启动成功");
                btnStart.Enabled = false;//按钮只能按一次
                //表示每次只能容纳10个,不代表总容量为10
                socketWatch.Listen(10);
                ////等待客户端连接Accept,并且返回一个负责通信的Socket
                //Socket socketSend=socketWatch.Accept();
                ////socketSend.RemoteEndPoint--返回连接客户端的IP地址
                //ShowMsg(socketSend.RemoteEndPoint.ToString()+":连接成功");
    
                //创建线程接收Listen函数
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch { }
        }
        //将连接的客户端的ip地址和SocketSend存入 键值对集合中
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        /// <summary>
        /// 等待客户端的 连接,并且创建一个与之通信的Socket
        /// </summary>
        /// <param name="obj"></param>
        void Listen(object obj)
        {
            Socket socketWatch = obj as Socket;//as做类型转换,如果返回的是Socket对象就是返回他,不是就返回null
           //用循环,一直等待客户端连接
            while (true)
            {
                try 
                { 
                    //等待客户端连接Accept,并且返回一个负责通信的Socket
                    socketSend = socketWatch.Accept();
    
                    //将连接的客户端的ip地址和SocketSend存入 键值对集合中
                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(),socketSend);
                    //客户端的ip地址存入下拉框
                    cboUser.Items.Add(socketSend.RemoteEndPoint.ToString());
                    //socketSend.RemoteEndPoint--返回连接客户端的IP地址
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":连接成功");
                    //下拉框默认选中第一个
                    cboUser.SelectedIndex = 0;
    
                    //开启一个新线程来接收客户端发过来的消息
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch { }
    
            }
        }
        /// <summary>
        /// 不停的接收客户端发过来的消息
        /// </summary>
        /// <param name="obj"></param>
        void Receive(object obj)
        {
            Socket socketSend = obj as Socket;
            while (true)
            {
                try 
                { 
                    //接收客户端发过来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //实际接收的数据r
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        //当r为0的时候表示用户下线,跳出接收循环
                        ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "已经下线");
                        break;
                    }
                    //将字节转换为字符
                    string msg = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + msg);
    
    
                    //将客户端的消息发回去
                    SendMsg(msg);
                }
                catch { }
            }
        }
        /// <summary>
        /// 服务器向客户端发信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string msg = txtSend.Text.Trim();
                //打印到自己的控制台中
                ShowMsg("服务器:"+msg);
                //将消息发给对方
                SendMsg(msg);
            }
            catch { }
        }
        /// <summary>
        /// 服务器向客户端发信息
        /// </summary>
        void SendMsg(string msg)
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
            List<byte> list = new List<byte>();
            list.Add(0);//表示发送的是文字
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();
            //buffer=list.toArray()//不能这样赋值,因为长度不一
            //获得用户下拉框选中的ip地址
            //cboUser.SelectedIndex = 0;
            string ip = cboUser.SelectedItem.ToString();
            dicSocket[ip].Send(newBuffer);
            //socketSend.Send(buffer);
            txtSend.Text = ""; //清空发送栏
        }
        /// <summary>
        /// 打印文字到TextBox中
        /// </summary>
        /// <param name="str"></param>
        void ShowMsg(string str)
        {
            //之所以不是Text,防止覆盖
            txtLog.AppendText(str + "\r\n");
        }
        /// <summary>
        /// 程序加载就取消跨线程访问
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 选择发送的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "请选择你要发送的文件";
                ofd.Filter = "文件文件|*.txt|图片文件|*.jpg|全部文件|*.*";
                ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
                ofd.ShowDialog();
                string path = ofd.FileName;
                txtPath.Text = path;//Path.GetFileName(path);
            }
            catch { }
        }
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                //获得发送文件的路径
                string path = txtPath.Text;
                if (path == "")
                {
                    return;
                }
                using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    byte[] buffer = new byte[1024 * 1024 * 100];
                    int r = fsRead.Read(buffer, 0, buffer.Length);
                    List<byte> listFile = new List<byte>();
                    listFile.Add(1);//1表示发送的是文件
                    listFile.AddRange(buffer);
                    byte[] newBuffer = listFile.ToArray();
                    dicSocket[cboUser.SelectedItem.ToString()].Send(newBuffer, 0, r+1, SocketFlags.None);
                }
            }
            catch { }
        }
    
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = new byte[1];
                buffer[0] = 2;
                dicSocket[cboUser.SelectedItem.ToString()].Send(buffer);
            }
            catch { }
    
        }
    
        private void cboUser_SelectedIndexChanged(object sender, EventArgs e)
        {
    
        }
    }
    

    }

    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用vmmare虚拟机用sentaurus仿真的时候,调用terminal程序,输入swb指令弹出这个,打不开workbench,桌面上面的sentaurus workbench也打不开
  • ¥75 使用winspool.drv的SetPrinter设置打印机失败
  • ¥15 simulink 硬件在环路仿真
  • ¥15 python动态规划:N根火柴摆出的最大数字
  • ¥20 (标签-excel)
  • ¥200 求idea10和MyEclipse7.1
  • ¥20 vb6.0截取当前窗体保存为jpg文件
  • ¥20 苹果手机不使用大疆sdk怎么获取遥控器控制信息或如何接入大疆sdk并且成功上架sdk
  • ¥20 woocommerce 注册按键重定向
  • ¥100 求书法图像文字切割代码