How to send a picture to the mail using mime and ssl - c#

I'm trying to send a letter with a picture to the mail, my code works with html files, pictures are sent, but when opened, it gives an error. I'm doing my lab work and on assignment I can't use MailMessage for example. I set the sending address from my windows forms.
using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
namespace NetworksNeLaba2
{
public class Program
{
private const string AddressFrom = "MYGM";
private const string PasswordFrom = "MYPS";
private static readonly Emailbox _emailbox = new Emailbox(AddressFrom, PasswordFrom);
private const string HostName = "smtp.gmail.com";
private const int Port = 465;
private static readonly ConnectionInstaller _connectionInstaller = new ConnectionInstaller(HostName, Port);
public static void Main(string[] args)
{
}
public void InitializeComponents(string address, string subject)
{
var direction = new MessageDirection(_emailbox.Address, address);
var commands = new []
{
$"EHLO {HostName}",
"AUTH LOGIN",
_emailbox.Address,
_emailbox.Password,
$"MAIL FROM:<{direction.From}>",
$"RCPT TO:<{direction.To}>",
"DATA"
};
var fileName = "cat.jpeg";
var ct = new ContentType();
ct.MediaType = MediaTypeNames.Image.Jpeg;
var data = new Attachment(fileName, ct.MediaType);
var s = data.ContentStream;
var reader = new StreamReader(s);
var letterContent = new []
{
$"Subject:{subject}\r\n",
$"From:Roma {AddressFrom}\r\n",
$"To:{address}\r\n",
$"Content-Type:{data.ContentType}\r\n",
$"Content-Disposition:{data.ContentDisposition}\r\n",
$"Content:{reader.ReadToEnd()}\r\n",
//$"Date:{DateTime.Now}\r\n",
".\r\n"
};
var letter = String.Concat(letterContent);
_connectionInstaller.SendMessage(commands, letter);
}
}
}
The first part of the code is what commands and the content of the letter I set, below I attached the code that processes the commands.
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
namespace NetworksNeLaba2
{
public class ConnectionInstaller
{
private readonly TcpClient _tcpClient = new TcpClient();
private readonly SslStream _sslStream;
private readonly byte[] _buffer = new byte[512];
public ConnectionInstaller(string hostName, int port)
{
_tcpClient.Connect(hostName, port);
_sslStream = new SslStream(_tcpClient.GetStream());
_sslStream.AuthenticateAsClient(hostName);
}
public void SendMessage(string[] commands,string letterContent)
{
foreach (var command in commands)
{
WriteBuffer(command + "\r\n");
}
WriteBuffer(letterContent);
}
private void WriteBuffer(string str)
{
_sslStream.Write(Encoding.ASCII.GetBytes(str));
_sslStream.Read(_buffer, 0, _buffer.Length);
Console.WriteLine(Encoding.ASCII.GetString(_buffer));
Array.Clear(_buffer, 0, _buffer.Length);
}
}
}

Related

NetMQ Unity Pub/Sub

I'm running into some issues trying to get NetMQ to work. My code compiles fine but I'm not achieving my desired outcome. Testing both Pub and Sub side from one PC.
I have a UI Handler that is linked to four buttons, start/stop pub/sub.
Would love if someone could shed some light into the issue.
Desired outcome: To be able to transfer test.wav from "Sending Folder" to "Receiving Folder"
Publisher Logic
using System.Threading;
using NetMQ;
using NetMQ.Sockets;
using System.IO;
public class Publisher
{
private readonly Thread _publisherThread;
private readonly Thread _subscriberThread;
public Publisher()
{
_publisherThread = new Thread(PublisherWork);
_publisherThread.Start();
_subscriberThread = new Thread(SubscriberWork);
_subscriberThread.Start();
}
public void Start()
{
using (var pubSocket = new PublisherSocket())
{
pubSocket.Bind("tcp://*:5557");
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Sending Folder/test.wav";
byte[] fileBytes = File.ReadAllBytes(filePath);
pubSocket.SendMoreFrame("File").SendFrame(fileBytes);
}
}
private void PublisherWork()
{
using (var pubSocket = new PublisherSocket())
{
pubSocket.Bind("tcp://*:5557"); // [C] Port
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Sending Folder/test.wav"; // [C] Filepath
byte[] fileBytes = File.ReadAllBytes(filePath);
while (true)
{
pubSocket.SendMoreFrame("File").SendFrame(fileBytes); // [C] Topic
Thread.Sleep(1000);
}
}
}
private void SubscriberWork()
{
using (var subSocket = new SubscriberSocket())
{
subSocket.Connect("tcp://localhost:5557"); // [C] Port
subSocket.Subscribe("File"); // [C] Topic
while (true)
{
var topic = subSocket.ReceiveFrameString();
var fileBytes = subSocket.ReceiveFrameBytes();
SaveWavFile(fileBytes);
}
}
}
private void SaveWavFile(byte[] fileBytes)
{
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Receiving Folder/test.wav";
File.WriteAllBytes(filePath, fileBytes);
}
}
Subscriber Logic
using System.Threading;
using NetMQ;
using NetMQ.Sockets;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class Subscriber : MonoBehaviour
{
public Button startButton;
public Button stopButton;
private Thread _publisherThread;
private Thread _subscriberThread;
private bool _isRunning;
private void Start()
{
startButton.onClick.AddListener(StartThreads);
stopButton.onClick.AddListener(StopThreads);
}
private void StartThreads()
{
_isRunning = true;
_publisherThread = new Thread(PublisherWork);
_publisherThread.Start();
_subscriberThread = new Thread(SubscriberWork);
_subscriberThread.Start();
}
private void StopThreads()
{
_isRunning = false;
_publisherThread.Join();
_subscriberThread.Join();
}
private void PublisherWork()
{
using (var pubSocket = new PublisherSocket())
{
pubSocket.Bind("tcp://*:5557"); // [C] Port
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Sending Folder/test.wav"; // [C] Filepath
byte[] fileBytes = File.ReadAllBytes(filePath);
while (_isRunning)
{
pubSocket.SendMoreFrame("File").SendFrame(fileBytes); // [C] Topic
Thread.Sleep(1000);
}
}
NetMQConfig.Cleanup();
}
private void SubscriberWork()
{
using (var subSocket = new SubscriberSocket())
{
subSocket.Connect("tcp://localhost:5557"); // [C] Port
subSocket.Subscribe("File"); // [C] Topic
while (_isRunning)
{
var topic = subSocket.ReceiveFrameString();
var fileBytes = subSocket.ReceiveFrameBytes();
SaveWavFile(fileBytes);
}
}
NetMQConfig.Cleanup();
}
private void SaveWavFile(byte[] fileBytes)
{
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Receiving Folder/test.wav"; // [C]
File.WriteAllBytes(filePath, fileBytes);
}
}
UI Handler
using System.Threading;
using NetMQ;
using NetMQ.Sockets;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class UIHandler : MonoBehaviour
{
public Button startSubscriberButton;
public Button stopSubscriberButton;
public Button startPublisherButton;
public Button stopPublisherButton;
public Text pubStartStatus;
public Text pubStopStatus;
public Text subStartStatus;
public Text subStopStatus;
private Publisher _publisher;
private readonly Thread _publisherThread;
private readonly Thread _subscriberThread;
private bool _publisherRunning = false;
private bool _subscriberRunning = false;
public UIHandler()
{
// Initializing the threads
_publisherThread = new Thread(PublisherWork);
_subscriberThread = new Thread(SubscriberWork);
}
private void Start()
{
_publisher = new Publisher();
startPublisherButton.onClick.AddListener(StartPublisher);
stopPublisherButton.onClick.AddListener(StopPublisher);
startSubscriberButton.onClick.AddListener(StartSubscriber);
stopSubscriberButton.onClick.AddListener(StopSubscriber);
}
public void StartPublisher()
{
// Starting the publisher thread
_publisherThread.Start();
_publisherRunning = true;
pubStartStatus.text = "pubStartStatus: Started";
}
public void StopPublisher()
{
// Stopping the publisher thread
_publisherRunning = false;
_publisherThread.Join();
pubStopStatus.text = "pubStartStatus: Stopped";
}
public void StartSubscriber()
{
// Starting the subscriber thread
_subscriberThread.Start();
_subscriberRunning = true;
subStartStatus.text = "subStartStatus: Stopped";
}
public void StopSubscriber()
{
// Stopping the subscriber thread
_subscriberRunning = false;
_subscriberThread.Join();
subStopStatus.text = "subStartStatus: Stopped";
}
private void PublisherWork()
{
// Creating a publisher socket and binding it to the specified address
using (var pubSocket = new PublisherSocket())
{
pubSocket.Bind("tcp://*:5557");
// Reading the file bytes from the specified location
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Sending Folder/test.wav";
byte[] fileBytes = File.ReadAllBytes(filePath);
// Publishing the file bytes continuously
while (_publisherRunning)
{
pubSocket.SendMoreFrame("File").SendFrame(fileBytes);
Thread.Sleep(1000);
}
}
NetMQConfig.Cleanup();
}
private void SubscriberWork()
{
// Creating a subscriber socket and connecting it to the specified address
using (var subSocket = new SubscriberSocket())
{
subSocket.Connect("tcp://localhost:5557");
subSocket.Subscribe("File");
// Receiving and saving the file bytes continuously
while (_subscriberRunning)
{
var topic = subSocket.ReceiveFrameString();
var fileBytes = subSocket.ReceiveFrameBytes();
SaveWavFile(fileBytes);
}
}
NetMQConfig.Cleanup();
}
private void SaveWavFile(byte[] fileBytes)
{
// Saving the received file bytes to the specified location
string filePath = "C:/Users/XXXXX/Desktop/0MQ Demo/Receiving Folder/test.wav";
File.WriteAllBytes(filePath, fileBytes);
}
}

How to fix when trying to add data values to a listbox from another form

I am having an issue while trying to add data to a listbox from my main form, I am trying to add data to that list from a new class in my project, I need that new class to be able to add data to my listbox without errors, I am trying to use a invoke and I am getting the following error (System.InvalidOperationException: 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.') I have seen that error in other questions in stack overflow but similar to my issue, I will be adding both classes of my code here, one is the main class and the other a second class I created that will need to add data to the listbox. the data is coming from a telnet tcp/ip and port 23 that connection is working fine, the problem is adding that data to my listbox.
Main class calling the functions from my other class
namespace BarcodeReceivingApp
{
//TelnetConnection stopConnection = new TelnetConnection();
public partial class BarcodeReceivingForm : Form
{
//GLOBAL VARIABLES
const string Hostname = "myip";
private const int Port = 23;
public BarcodeReceivingForm()
{
InitializeComponent();
}
private void btn_ConnectT_Click(object sender, EventArgs e)
{
var readData = new TelnetConnection(Hostname, Port);
readData.ServerSocket(Hostname, Port);
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
//var connection = new TelnetConnection(Hostname, Port);
// connection.CloseConnection();
}
}
}
class that will change the data of my listbox from the main class.
namespace BarcodeReceivingApp
{
public class TelnetConnection
{
public BarcodeReceivingForm BcForm = new BarcodeReceivingForm();
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port)
{
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
//Assign networkstream
_networkStream = _client.GetStream();
//start socket read/write thread
_readWriteThread = new Thread(ReadWrite);
_readWriteThread.Start();
}
public void ReadWrite()
{
//Set up connection loop
while (true)
{
var command = "test";
if (command == "STOP1")
break;
//write(command);
var received = Read();
BcForm.lst_BarcodeScan.Invoke(new Action (() => BcForm.lst_BarcodeScan.Items.Add(received)));
}
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
_networkStream.Close();
_client.Close();
}
}
}
the final results like I said is my ReadWrite method when running the loop will add the data to my listbox from my main form class
here the image where I get the error
Image of Error
Write your second class like this
using System;
using System.Threading;
using System.Windows.Forms;
namespace BarcodeReceivingApp {
public class TelnetConnection {
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
private Form foo;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port,Form f)
{
this.foo = f;
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
_networkStream = _client.GetStream();
_readWriteThread = new Thread(ReadWrite());
_readWriteThread.Start();
}
public void ReadWrite()
{
while (true)
{
var command = "test";
if (command == "STOP1")
break;
//write(command);
var received = Read();
if (foo.lst_BarcodeScan.InvokeRequired)
{
foo.lst_BarcodeScan.Invoke(new MethodInvoker(delegate {foo.lst_BarcodeScan.Items.Add(received);}));
}
}
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
_networkStream.Close();
_client.Close();
}
}
}
Then use it like this from your main class:
private void btn_ConnectT_Click(object sender, EventArgs e)
{
var readData = new TelnetConnection(Hostname, Port);
readData.ServerSocket(Hostname, Port, this);
}

Handle all Events for an aggregate

Please see my first Persistent Subscription below:
namespace PersistentSubscription
{
internal class Program
{
private static void Main()
{
var subscription = new PersistentSubscriptionClient();
subscription.Start();
}
}
public class PersistentSubscriptionClient
{
private IEventStoreConnection _conn;
private const string STREAM = "$ce-customer";
private const string GROUP = "a_test_group";
private const int DEFAULTPORT = 1113;
private static readonly UserCredentials User = new UserCredentials("admin", "changeit");
private EventStorePersistentSubscriptionBase _subscription;
public void Start()
{
var settings = ConnectionSettings.Create();
using (_conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
{
_conn.ConnectAsync().Wait();
CreateSubscription();
ConnectToSubscription();
Console.WriteLine("waiting for events. press enter to exit");
Console.ReadLine();
}
}
private void ConnectToSubscription()
{
var bufferSize = 10;
var autoAck = true;
Action<EventStorePersistentSubscriptionBase, ResolvedEvent> eventAppeared = EventAppeared;
_subscription = _conn.ConnectToPersistentSubscription(STREAM, GROUP, eventAppeared, SubscriptionDropped, User, bufferSize, autoAck);
}
private void SubscriptionDropped(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
SubscriptionDropReason subscriptionDropReason, Exception ex)
{
ConnectToSubscription();
}
private static void EventAppeared(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
ResolvedEvent resolvedEvent)
{
MemoryStream stream = new MemoryStream(resolvedEvent.Event.Data);
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
try
{
CustomerCreated customerCreated = (CustomerCreated)formatter.Deserialize(stream);
Console.WriteLine(customerCreated);
}
catch (Exception e)
{
var test = "test";
}
}
private void CreateSubscription()
{
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent();
try
{
_conn.CreatePersistentSubscriptionAsync(STREAM, GROUP, settings, User).Wait();
}
catch (AggregateException ex)
{
if (ex.InnerException.GetType() != typeof(InvalidOperationException)
&& ex.InnerException?.Message != $"Subscription group {GROUP} on stream {STREAM} already exists")
{
throw;
}
}
}
}
}
and my first client below:
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using EventStore.ClientAPI;
namespace WritingEvents
{
class Program
{
static void Main(string[] args)
{
const int DEFAULTPORT = 1113;
var settings = ConnectionSettings.Create();
using (var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
{
conn.ConnectAsync().Wait();
CustomerCreated c1 = new CustomerCreated { Id = Guid.NewGuid(), Name = "Maria" };
EventData customerCreated1 = GetEventDataFor(c1);
conn.AppendToStreamAsync("customer-100", ExpectedVersion.Any, customerCreated1).Wait();
}
}
private static EventData GetEventDataFor(CustomerCreated customerCreated)
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, customerCreated);
byte[] customerCreatedEventByteArray = stream.ToArray();
return new EventData(
Guid.NewGuid(),
"eventType",
true,
customerCreatedEventByteArray,
null
);
}
}
[Serializable]
public class CustomerCreated
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
I run the server and then then the client. I see an error when deserializing the CustomerCreated event on the server side. The error is: "End of stream was encountered before parsing was completed".
If I change this line:
private const string STREAM = "$ce-customer";
to this:
private const string STREAM = "customer-100";
Then deserialization works correctly on the server side.
How do I handle all customer events - not just customer 100?
I have --run-projections=all when starting Event Store. I have also enabled all projections:
This question helped me: Using the Event Store Client API (.NET), how to I write to a stream and link one event to another?
I simply had to change this:
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos() //Specifically this line
.StartFromCurrent();
to this:
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.ResolveLinkTos() //Specifically this line
.StartFromCurrent();
DoNotResolveLinkTos gets a link to the original event, whereas ResolveLinkTos gets the actual event itself. Therefore I was trying to deserialize the link object, which was causing the exception.

C# WPF Anonymous Pipes AnonymousPipeClientStream pipe direction out doesn't work

I'm developing a test application to communicate between 2 processes using Anonymous Pipes. I can send a message to the ClientView from the ServerView but I can't do the other way round since the pipe connection throws exceptions.
ServerCode
public class PipeServerHandler
{
private static AnonymousPipeServerStream serverSenderStream;
private static AnonymousPipeServerStream serverReceiverStream;
private static StreamWriter sw;
private static StreamReader sr;
public void ServerStart()
{
serverSenderStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
serverReceiverStream = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
string senderID = serverSenderStream.GetClientHandleAsString();
string receiverID = serverReceiverStream.GetClientHandleAsString();
ProcessStartInfo process = new ProcessStartInfo(#"C:\Users\VinushaP\Documents\Visual Studio 2015\Projects\CommunicationProject\ClientView\bin\Debug\ClientView.exe", senderID + "_" + receiverID);
process.UseShellExecute = false;
Process clientProcess = Process.Start(process);
serverSenderStream.DisposeLocalCopyOfClientHandle();
sr = new StreamReader(serverReceiverStream);
}
public string ReadData()
{
string temp;
temp = sr.ReadLine();
return temp;
}
}
Client Code
public class PipeClientHandler
{
private static AnonymousPipeClientStream clientReceiverStream;
private static AnonymousPipeClientStream clientSenderStream;
private static StreamReader sr;
private static StreamWriter sw;
public void ClientStart(string[] args)
{
string[] id = args[0].Split('_');
string senderID = id[0];
string receiverID = id[1];
clientReceiverStream = new AnonymousPipeClientStream(PipeDirection.In, senderID);
clientSenderStream = new AnonymousPipeClientStream(PipeDirection.Out, receiverID);
sw = new StreamWriter(clientSenderStream);
sw.AutoFlush = true;
}
public void WriteStream(string data)
{
sw.WriteLine(data);
clientSenderStream.WaitForPipeDrain();
}
}
This is the app.xaml.cs class which captures the Command Line args
private void Application_Startup(object sender, StartupEventArgs e)
{
PipeClientHandler handler = new PipeClientHandler();
if (e.Args.Length > 0)
{
handler.ClientStart(e.Args);
}
}
When sending data from PipeServerHandler to PipeClienHandler it works well, but when I send data from PipeClientHandler to PipeServerHandler it doesn't show me any messages.
clientSenderStream error
Anonymous pipes are one way. You'll need two anonymous pipes to do 2 way communications.

sending data using udp

i am using those scripts bellow to send and receive data, when i send data from an android support to my computer i can't receive anything !!! i can't find the problem can anyone help me please
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPSend : MonoBehaviour
{
public string IP = "myIP"; // default local
public int port = 26000;
IPEndPoint remoteEndPoint;
UdpClient client;
string strMessage="";
public void Start()
{
init();
}
void OnGUI()
{
Rect rectObj=new Rect(40,380,200,400);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,"UDPSendData\n IP : "+IP+" Port : "+port,style);
//
strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
if (GUI.Button(new Rect(190,420,40,20),"Send"))
{
sendString(strMessage+"\n");
}
}
// init
public void init()
{
IP="myIP";
port=26000; // quake port ;)
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
//remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, port); // toute machine
client = new UdpClient();
}
// sendData
private void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
void OnDisable()
{
if ( client!= null) client.Close();
}
}
UDPReceive:
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net.NetworkInformation;
public class UDPReceive : MonoBehaviour {
Thread receiveThread;
UdpClient client;
public int port = 26000;
string strReceiveUDP="";
string LocalIP = String.Empty;
string hostname;
public void Start()
{
Application.runInBackground = true;
init();
}
// init
private void init()
{
receiveThread = new Thread( new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
hostname = Dns.GetHostName();
IPAddress[] ips = Dns.GetHostAddresses(hostname);
if (ips.Length > 0)
{
LocalIP = ips[0].ToString();
}
}
void OnGUI()
{
Rect rectObj=new Rect(10,10,400,200);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,hostname+" MY IP : "+LocalIP+" : "+strReceiveUDP,style);
}
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, port);
//IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
strReceiveUDP = text;
//Debug.Log(strReceiveUDP);
}
catch (Exception err)
{
print(err.ToString());
}
}
}
public string UDPGetPacket()
{
return strReceiveUDP;
}
void OnDisable()
{
if ( receiveThread!= null) receiveThread.Abort();
client.Close();
}
}
When myIP is 127.0.0.1 everything works normally

Categories

Resources