Соединение COM портов. Подключения создаются, но сервер и клиент друг друга не видят - C#
Формулировка задачи:
имеется класс с методами подключения:
имеется клиент:
имеется сервер:
Подключения создаются, но друг друга не видят
порты виртуальные, создаются при помощи вот этой штуки
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.IO.Pipes;
using System.Security.Principal;
using System.IO.Ports;
[Guid("FB8253D0-BECC-4e94-9B48-BCAB62BAAE3B")]
public interface ICom
{
[DispId(1)]
bool Connect(string PortName);
void Disconnect();
string Receive();
void Send(string message);
}
[Guid("A05EB863-5126-43d6-8D8B-202BFA543D80"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
}
[Guid("B1C0F778-2A43-4928-9F47-D82FF4FB75DB"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(IComEvents))]
public class portCom : ICom
{
SerialPort port;
public bool Connect(string PortName)
{
port = new SerialPort();
port.PortName = PortName;
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.DtrEnable = true;
port.RtsEnable = true;
port.ReadTimeout = 10000;
port.WriteTimeout = 10000;
port.Open();
return true;
}
public void Disconnect()
{
try
{
port.Close();
}
catch (Exception)
{ }
}
public string Receive()
{
byte[] bytes = new byte[1024];
int length = port.Read(bytes, 0, bytes.Length);
return Encoding.UTF8.GetString(bytes, 0, length);
}
public void Send(string message)
{
byte[] log = Encoding.UTF8.GetBytes(message);
port.Write(log, 0, log.Length);
}
}using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.IO.Ports;
public class AsynchronousSocketClient
{
public static void StartClient()
{
string word = null;
try
{
Console.WriteLine("Идет поиск сервера...");
portCom client = new portCom();
client.Connect("COM1");
Console.WriteLine("Успешно подключен");
bool flag = true;
while (flag)
{
Console.WriteLine("Системное сообщение: {0}", client.Receive());
word = Console.ReadLine();
client.Send(word);
if (word == "quit")
{
flag = false;
}
}
client.Disconnect();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static int Main(String[] args)
{
StartClient();
Console.ReadLine();
return 0;
}
}using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
public class SocketListener
{
private static int threadCount = 10;
public static string data = null;
public static string reciveLogin = null;
public static string recivePass = null;
public static string loginMsg = null;
public static string done = null;
static List<string> name = new List<string>();
static List<string> pass = new List<string>();
static bool flag;
static bool logined;
static bool newClient;
public static Mutex mut = new Mutex();
public static Mutex mutex = new Mutex();
static void newAccount(object hand)
{
portCom handler = (portCom)hand;
mut.WaitOne();
// Просим логин
loginMsg = "Введите логин: ";
handler.Send(loginMsg);
// Принимаем логин
reciveLogin = handler.Receive();
name.Add(reciveLogin);
Console.WriteLine("Зарегестрированный логин от клиента {0}: {1}", Thread.CurrentThread.Name, reciveLogin);
//Просим пароль
loginMsg = "Введите пароль: ";
handler.Send(loginMsg);
//Принимаем пароль
recivePass = handler.Receive();
pass.Add(recivePass);
Console.WriteLine("Зарегестрированный пароль от клиента {0}: {1}", Thread.CurrentThread.Name, recivePass);
mut.ReleaseMutex();
logined = false;
flag = true;
}
static void newLog(object hand)
{
portCom handler = (portCom)hand;
bool log_fl = true;
mut.WaitOne();
while (log_fl)
{
// Просим логин
loginMsg = "Логин: ";
handler.Send(loginMsg);
// Принимаем логин
reciveLogin = handler.Receive();
Console.WriteLine("Полученный логин от клиента {0}: {1}", Thread.CurrentThread.Name, reciveLogin);
//Просим пароль
loginMsg = "Пароль: ";
handler.Send(loginMsg);
//Принимаем пароль
recivePass = handler.Receive();
Console.WriteLine("Полученный пароль от клиента {0}: {1}", Thread.CurrentThread.Name, recivePass);
for (int i = 0; i < name.Count; i++)
{
if (reciveLogin == name[i] && recivePass == pass[i])
{
log_fl = false;
break;
}
}
}
mut.ReleaseMutex();
flag = true;
logined = false;
}
static void newConnect(object hand)
{
mutex.WaitOne();
portCom server = new portCom();
try
{
bool a = false;
do { a = server.Connect("COM2");} while(a == false);
Console.WriteLine("Клиент номер {0} успешно подключен", Thread.CurrentThread.Name);
// newClient = true;
flag = true;
string text = null;
string dect;
logined = false;
Thread threadReg = new Thread(newAccount);
Thread threadLog = new Thread(newLog);
// Выбор регистрация или логин
while (true)
{
if (flag)
{
data = null;
reciveLogin = null;
recivePass = null;
text = "\n1-Регистрация\n2-Вход";
server.Send(text);
dect = server.Receive();
if (dect == "1")
{
threadReg.Start(server);
flag = false;
}
else if (dect == "2")
{
threadLog.Start(server);
logined = true;
flag = false;
}
}
if (logined) break;
}
while (true)
{
if (flag)
{
data = null;
data = "Введите команду: ";
server.Send(data);
data = server.Receive();
Console.WriteLine("Полученый текст от клиента {0}: {1}", Thread.CurrentThread.Name, data);
if (data == "quit")
{
server.Disconnect();
Thread.CurrentThread.Interrupt();
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Клиент номер {0} отключен", Thread.CurrentThread.Name);
}
mutex.ReleaseMutex();
}
public static void StartListening()
{
string testLogin = "a";
string testPass = "s";
logined = false;
flag = true;
name.Add(testLogin);
pass.Add(testPass); //int index = 1;
Thread[] servers = new Thread[threadCount];
newClient = true;
Console.WriteLine("Ожидание подключения...");
for (int i = 0; i < threadCount; i++)
{
while (!newClient) { }
servers[i] = new Thread(newConnect) { Name = (i + 1).ToString() };
servers[i].Start();
newClient = false;
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}Решение задачи: «Соединение COM портов. Подключения создаются, но сервер и клиент друг друга не видят»
textual
Листинг программы
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.IO.Pipes;
using System.Security.Principal;
using System.IO.Ports;
[Guid("FB8253D0-BECC-4e94-9B48-BCAB62BAAE3B")]
public interface ICom
{
[DispId(1)]
void Connect(string PortName);
void Disconnect();
string Receive();
void Send(string message);
}
[Guid("A05EB863-5126-43d6-8D8B-202BFA543D80"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
}
[Guid("B1C0F778-2A43-4928-9F47-D82FF4FB75DB"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(IComEvents))]
public class portCom : ICom
{
SerialPort port;
public void Connect(string PortName)
{
port = new SerialPort();
port.PortName = PortName;
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.RtsEnable = true;
port.ReadTimeout = 100000;
port.WriteTimeout = 100000;
port.Open();
}
public void Disconnect()
{
do
{
try
{
port.Close();
}
catch (Exception) { }
} while (port.IsOpen);
}
public string Receive()
{
try
{
return port.ReadLine();
}
catch (Exception)
{
return "";
}
}
public void Send(string message)
{
try
{
port.WriteLine(message);
}
catch (Exception) { }
}
}