就是自己的電腦是連接路由器的,但是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 + "\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)
{
}
}
}