基本信息
源码名称:C# 基于服务器的客户端相互直接通信(tcp连接)
源码大小:0.14M
文件格式:.zip
开发语言:C#
更新时间:2017-06-11
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
实验内容:基于服务器的客户端相互直接通信
具体要求包括:
1,Server支持多客户访问;
2,C与S之间使用TCP连接;
3,C与C之间直接通信(不是通过S传递)。
4,C与C之间直接通信既可以使用TCP,也可以使用UDP。
5,可以使用Socket,也可以使用TcpClient/UdpClient等;
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 SyncChatClient
{
public partial class Client : Form
{
private bool isExit = false;
private TcpClient client;
private BinaryReader br;
private BinaryWriter bw;
private List<User> userList = new List<User>();
private TcpListener myListener;
IPAddress localAddress;
private static int myport;
public Client()
{
InitializeComponent();
Random r = new Random((int)DateTime.Now.Ticks);
textBoxUserName.Text = "User" r.Next(100, 999);
listBoxOnline.HorizontalScrollbar = true;
//---------------------c-c----------------------------------
IPAddress[] addrIP = Dns.GetHostAddresses(Dns.GetHostName());
localAddress = addrIP[0];
while (true)
{
myport = r.Next(2049, 8888);
try
{
myListener = new TcpListener(localAddress, myport);
break;
}
catch
{
//如果端口不可用
}
}
myListener.Start();
Thread myThread = new Thread(ListenClientConnect);
myThread.IsBackground=true;
myThread.Start();
}
//---------------------c-c----------------------------------
private void ListenClientConnect()
{
TcpClient newClient = null;
while (true)
{
try
{
newClient = myListener.AcceptTcpClient();
}
catch
{
break;
}
User user = new User(newClient);
Thread threadReceive = new Thread(ServerReceive);
threadReceive.Start(user);
threadReceive.IsBackground = true;
}
}
//---------------------c-c----------------------------------
private void ServerReceive(Object userState) //客户端充当server的接收方法
{
User user = (User)userState ;//////////////////////////////////////////
TcpClient client = user.client;
while (isExit == false)
{
string receiveString = null;
try
{
receiveString = user.br.ReadString();
AddTalkMessage(receiveString);
}
catch
{
if (isExit == false)
{
user.Close();
AddTalkMessage("接收信息失败");
}
break;
}
}
user.Close();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
buttonConnect.Enabled = false;
try
{
client = new TcpClient(Dns.GetHostName(), 51888);
AddTalkMessage("连接成功");
NetworkStream networkStream = client.GetStream();
br = new BinaryReader(networkStream);
bw = new BinaryWriter(networkStream);
SendMessage("Login," textBoxUserName.Text "," localAddress "," myport);
Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
threadReceive.IsBackground = true;
threadReceive.Start();
}
catch
{
AddTalkMessage("连接失败");
buttonConnect.Enabled = true;
return;
}
AddOnline("Server"); //添加在线者——Server
}
private void ReceiveData() //客户端是client的接收方法
{
string receiveString = null;
while (isExit == false)
{
try
{
receiveString = br.ReadString();
}
catch
{
if (isExit == false)
{
MessageBox.Show("与服务器失去联系。");
}
break;
}
string[] splitString = receiveString.Split(',');
string command = splitString[0].ToLower();
switch (command)
{
case "login":
AddOnline(receiveString);
break;
case "logout":
RemoveUserName(splitString[1]);
break;
case "talk":
AddTalkMessage(splitString[1] "对我说:" receiveString.Substring(splitString[0].Length splitString[1].Length 2));
break;
default:
AddTalkMessage("什么意思啊:" receiveString);
break;
}
}
Application.Exit();
}
private void SendMessage(string message)
{
try
{
bw.Write(message);
bw.Flush();
}
catch
{
AddTalkMessage("发送失败!");
}
}
private delegate void MessageDelegate(string message);
private void AddTalkMessage(string message)
{
if (richTextBoxTalkInfo.InvokeRequired)
{
MessageDelegate d = new MessageDelegate(AddTalkMessage);
richTextBoxTalkInfo.Invoke(d, new object[] { message });////////////
}
else
{
richTextBoxTalkInfo.AppendText(message Environment.NewLine);
richTextBoxTalkInfo.ScrollToCaret();
}
}
private delegate void AddOnlineDelegate(string message);
private void AddOnline(string message) //把新用户添加道listBox并储存在userList中(保存ip端口)
{
if (message == "Server")
{
if (listBoxOnline.InvokeRequired)
{
AddOnlineDelegate d = new AddOnlineDelegate(ToAddOnline);
listBoxOnline.Invoke(d, message);
}
else
{
ToAddOnline(message);
}
User u = new User("Server", Dns.GetHostName(), 51888);
userList.Add(u);
return;
}
string[] splitString = message.Split(',');
int port1;
if (listBoxOnline.InvokeRequired)
{
AddOnlineDelegate d = new AddOnlineDelegate(ToAddOnline);
listBoxOnline.Invoke(d, splitString[1]);
}
else
{
ToAddOnline(splitString[1]);
}
port1 = int.Parse(splitString[3]);
User user = new User(splitString[1], splitString[2], port1);
userList.Add(user);
}
private void ToAddOnline(string message)
{
listBoxOnline.Items.Add(message);
listBoxOnline.SelectedIndex = listBoxOnline.Items.Count - 1;
listBoxOnline.ClearSelected();
}
private delegate void RemoveUserNameDelegate(string userName);
private void RemoveUserName(string userName)
{
if (listBoxOnline.InvokeRequired)
{
RemoveUserNameDelegate d = RemoveUserName;
listBoxOnline.Invoke(d, userName);
}
else
{
listBoxOnline.Items.Remove(userName);
listBoxOnline.SelectedIndex = listBoxOnline.Items.Count - 1;
listBoxOnline.ClearSelected();
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (listBoxOnline.SelectedIndex != -1)
{
SendMessage("Talk," listBoxOnline.SelectedItem "," textBoxSend.Text);
AddTalkMessage("我对" listBoxOnline.SelectedItem "说:" textBoxSend.Text);
textBoxSend.Clear();
}
else
{
MessageBox.Show("请先在[当前在线]中选择一个对话者");
}
}
private void Client_FormClosing(object sender, FormClosingEventArgs e)
{
if (client != null)
{
SendMessage("Logout," textBoxUserName.Text);
isExit = true;
br.Close();
bw.Close();
client.Close();
}
}
private void Client_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char)Keys.Return)
{
buttonSend.PerformClick();
}
}
private void buttonTcpSend_Click(object sender, EventArgs e)
{
User myUser;
if (listBoxOnline.SelectedIndex != -1)
{
for(int i = 0; i < listBoxOnline.SelectedItems.Count; i )
{
foreach(User u in userList)
{
if (u.userName.Equals("Server"))
{
//
}
else if (u.userName.Equals(listBoxOnline.SelectedItems[i].ToString()))
{
try
{
IPAddress ip = IPAddress.Parse(u.ip);
///IPEndPoint iep = new IPEndPoint(ip, u.port);
//TcpClient myClient = new TcpClient();
//myClient.Connect(iep); //connect一直出错,ip没问题,奇怪
TcpClient myClient = new TcpClient(Dns.GetHostName(), u.port);
myUser = new User(myClient);
myUser.bw.Write(textBoxUserName.Text "向我发来TCP消息:" textBoxSend.Text);
}
catch
{
AddTalkMessage("发送失败");
}
}
}
AddTalkMessage("向" listBoxOnline.SelectedItem "发送TCP消息:" textBoxSend.Text);
}
textBoxSend.Clear();
}
else
{
MessageBox.Show("请先在[当前在线]中选择一个对话者");
}
}
}
}