问题描述
- C#客户端为什么连接不上服务器,当ip地址为127.0.0.1是没有问题的
-
就是自己的电脑是连接路由器的,但是ip不是192.168.开头的,不知道是公网问题还是什么问题,测试都是用自己的一台电脑的。
解决方案
服务端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 + "
");
}
/// <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:UsersAdministratorDesktop";
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)
{
}
}
}
解决方案二:
服务端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 + "
");
}
/// <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:UsersAdministratorDesktop";
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)
{
}
}
}
解决方案三:
客户端Client
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 Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socketSend;
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
//创建负责通信的Socket通信
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txtIp.Text);
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
///服务器没有连接会抛异常
//连接 ---获得要连接服务器的IP地址和端口
socketSend.Connect(point);
ShowMsg("连接成功");
btnConnect.Enabled = false;
//开启一个新的线程接收客户端发过的消息
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}
catch { }
}
/// <summary>
/// 把消息显示到txtlog中
/// </summary>
/// <param name="str"></param>
void ShowMsg(string str)
{
txtLog.AppendText(str+"
");
}
/// <summary>
/// 客户端给服务端发送信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
try
{
string msg = txtSend.Text.Trim();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
socketSend.Send(buffer);
//程序关闭应该提示下线
txtSend.Text = "";//清空发送栏
}
catch { }
}
/// <summary>
/// 不停的接收服务器发过来的消息
/// </summary>
void Receive()
{
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 100];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
//判断 0表示的是发送文字消息,1表示文件,2表示震动
if (buffer[0] == 0)
{
string msg = Encoding.UTF8.GetString(buffer, 1, r-1);//(buffer, 0, r);
//判断是谁发过来的消息
string UserName = socketSend.RemoteEndPoint.ToString();
if (UserName == socketSend.RemoteEndPoint.ToString())
{
}
ShowMsg(UserName + ":" + msg);
}
else if (buffer[0] == 1)
{
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "请选择保存的路径";
sfd.Filter = "文本文件|*.txt|图片文件|*.jpg|全部文件|*.*";
sfd.InitialDirectory = @"C:UsersAdministratorDesktop";
sfd.ShowDialog(this);
//sfd.FileName表示接受过来的文件的路径-- 将接受的文件保存到桌面
string path = sfd.FileName;//@"C:UsersAdministratorDesktop";//sfd.fileName
if (path == "")
{
return;
}
using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
fsWrite.Write(buffer, 1, r - 1);
}
MessageBox.Show("保存成功");
}
catch{ }
}
else if (buffer[0] == 2)
{
ZhenDong();
}
}
catch { }
}
}
/// <summary>
/// 震动
/// </summary>
void ZhenDong()
{
for (int i = 0; i < 500; i++)
{
this.Location = new Point(400,100);
this.Location = new Point(180,180);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
解决方案四:
在C#中服务端如何获取客户端的IP地址、端口号以及客户端和服务器连接的时间
解决方案五:
不论是WIN7还是WIN10防火墙默认都是开的,除非你用的是网吧那种光盘做的系统,百度一下,如何windows添加端口访问规则
解决方案六:
另外一台电脑 telnet 192.168.X.XXX port,估计是无法连接,百度防火墙吧