本文整理汇总了C#中Windows.Networking.Sockets.StreamSocket.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# StreamSocket.Dispose方法的具体用法?C# StreamSocket.Dispose怎么用?C# StreamSocket.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Networking.Sockets.StreamSocket
的用法示例。
在下文中一共展示了StreamSocket.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConnectAsync
public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args)
{
_socket = new StreamSocket();
var server = new HostName(ipOrHost);
// TCP timeouts in WinRT are excessive, shorten them here using task cancellation
var cts = new CancellationTokenSource();
try
{
cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000);
_logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName));
await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token);
_clientUid = args.ClientUid;
StartReceiving();
}
catch (TaskCanceledException)
{
args.SocketException = new IOException("Timeout error while trying to connect.");
_clientUid = null;
_socket.Dispose();
_socket = null;
}
catch (Exception ex)
{
args.SocketException = ex;
_clientUid = null;
_socket.Dispose();
_socket = null;
}
args.Complete();
}
示例2: CheckServerAddressWP
public static async Task<bool> CheckServerAddressWP(string url, int port = 80, int msTimeout = 5000)
{
bool retVal = false;
string originalUrl = url;
if (!IsUrlValid(url))
return retVal;
try
{
using (var tcpClient = new StreamSocket())
{
url = url.Replace("http://", string.Empty).Replace("https://", string.Empty);
if (url.Last() == '/')
url = url.Substring(0, url.Length - 1);
await tcpClient.ConnectAsync(new Windows.Networking.HostName(url), port.ToString(), SocketProtectionLevel.PlainSocket);
if (tcpClient.Information.RemoteHostName.ToString().ToLower() == url.ToLower())
retVal = true;
tcpClient.Dispose();
}
}
catch (Exception ex)
{
retVal = false;
}
retVal &= await ExposesContosoMomentsWebAPIs(originalUrl);
return retVal;
}
示例3: ReceiveImage
private async void ReceiveImage(StreamSocket socket)
{
// DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
var reader = new DataReader(socket.InputStream);
// Anzahl der Bytes abrufen, aus denen das Bild besteht
// Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
await reader.LoadAsync(4);
int imageSize = reader.ReadInt32();
// Bytearray des Bildes laden
await reader.LoadAsync((uint)imageSize);
byte[] imageBytes = new byte[imageSize];
reader.ReadBytes(imageBytes);
// Bytearray in Stream laden und anzeigen
using (var ms = new MemoryStream(imageBytes))
{
var image = new BitmapImage();
image.SetSource(ms);
ReceivedImage.Source = image;
}
Status.Text = "Bild empfangen.";
// Ressourcen freigeben
reader.Dispose();
socket.Dispose();
}
示例4: ProcessRequestAsync
private async void ProcessRequestAsync(StreamSocket socket)
{
HttpRequest request;
try
{
request = HttpRequest.Read(socket);
}
catch (Exception ex)
{
await WriteInternalServerErrorResponse(socket, ex);
return;
}
if (AcceptedVerbs.Contains(request.Method.Method))
{
HttpResponse response;
try
{
response = await restHandler.Handle(request);
}
catch (Exception ex)
{
await WriteInternalServerErrorResponse(socket, ex);
return;
}
await WriteResponse(response, socket);
await socket.CancelIOAsync();
socket.Dispose();
}
}
示例5: Connect
public static void Connect(string address, string port)
{
if (!connected)
{
clientSocket = new StreamSocket();
try
{
serverHost = new HostName(address);
serverPort = port;
serverHostnameString = address;
writer = new DataWriter(clientSocket.OutputStream);
clientSocket.ConnectAsync(serverHost, serverPort);
connected = true;
}
catch (Exception)
{
clientSocket.Dispose();
clientSocket = null;
throw new ConnectionErrorException();
}
}
else
{
clientSocket.Dispose();
clientSocket = null;
connected = false;
GamepadClient.Connect(address, port);
}
}
示例6: ConnectTo
public async void ConnectTo(Slide slide)
{
var duration = slide.AppearanceDuration;
var content = slide.Content as ScreenCapture;
var ipAddress = content.IPTargetAgent;
HostName localHost = null;
foreach (var hostName in NetworkInformation.GetHostNames())
{
if(hostName.IPInformation != null)
{
if(hostName.Type == Windows.Networking.HostNameType.Ipv4)
{
localHost = hostName;
}
}
}
var TCPClient = new StreamSocket();
try
{
var cts = new CancellationTokenSource();
cts.CancelAfter(500);
var connectAsync = TCPClient.ConnectAsync(
new Windows.Networking.EndpointPair(localHost, "54321", new Windows.Networking.HostName(ipAddress), "54321"));
var connectTask = connectAsync.AsTask(cts.Token);
await connectTask;
this.SendToAgent(slide, TCPClient);
}
catch(Exception ex)
{
TCPClient.Dispose();
Debug.WriteLine(ex.Message);
this.FireOnConnectionFailed();
return;
}
}
示例7: StartAsync
public async Task StartAsync()
{
if (tcs != null)
return;
if (m_device == null)
throw new ObjectDisposedException("Device");
tcs = new System.Threading.CancellationTokenSource();
socket = new StreamSocket();
await socket.ConnectAsync(
#if NETFX_CORE
m_device.ConnectionHostName,
m_device.ConnectionServiceName);
#else
m_device.HostName, "1");
//socket = await Windows.Networking.Proximity.PeerFinder.ConnectAsync(m_device.HostName;
#endif
if (tcs.IsCancellationRequested) //Stop was called while opening device
{
socket.Dispose();
socket = null;
throw new TaskCanceledException();
} var token = tcs.Token;
var _ = Task.Run(async () =>
{
var stream = socket.InputStream.AsStreamForRead();
byte[] buffer = new byte[1024];
while (!token.IsCancellationRequested)
{
int readCount = 0;
try
{
readCount = await stream.ReadAsync(buffer, 0, 1024, token).ConfigureAwait(false);
}
catch { }
if (token.IsCancellationRequested)
break;
if (readCount > 0)
{
OnData(buffer.Take(readCount).ToArray());
}
await Task.Delay(10, token);
}
if(socket != null)
socket.Dispose();
if (closeTask != null)
closeTask.SetResult(true);
});
}
示例8: ConnectAsync
public async Task ConnectAsync(Uri url, CancellationToken cancellationToken)
{
var host = url.Host;
var serviceName = url.Port.ToString(CultureInfo.InvariantCulture);
var hostName = new HostName(host);
var useTls = string.Equals("HTTPS", url.Scheme, StringComparison.OrdinalIgnoreCase);
if (!useTls && !string.Equals("HTTP", url.Scheme, StringComparison.OrdinalIgnoreCase))
throw new NotSupportedException("Scheme not supported: " + url.Scheme);
var socket = new StreamSocket();
if (null != Interlocked.CompareExchange(ref _socket, socket, null))
{
socket.Dispose();
throw new InvalidOperationException("The socket is in use");
}
try
{
socket.Control.NoDelay = true;
#if WINDOWS_PHONE8
var protectionLevel = useTls ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket;
#else
var protectionLevel = useTls ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
#endif
await socket.ConnectAsync(hostName, serviceName, protectionLevel)
.AsTask(cancellationToken)
.ConfigureAwait(false);
}
catch (Exception)
{
Close();
throw;
}
//if (useTls)
//{
// var cert = socket.Information.ServerCertificate;
// var certFingerprint = cert.GetHashValue("SHA256");
//}
}
示例9: HandleRequest
private async void HandleRequest(StreamSocket socket) {
//Initialize IO classes
var reader = new DataReader(socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial };
var writer = new DataWriter(socket.OutputStream) {
UnicodeEncoding = UnicodeEncoding.Utf8
};
var acceptedRequest = new AcceptedRequest();
await acceptedRequest.AcceptRequest(reader);
String response = ProcessRequest(acceptedRequest.request, acceptedRequest.content);
//create response
writer.WriteString(Responder.CreateResponse(response));
await writer.StoreAsync();
socket.Dispose();
}
示例10: ConnectAsync
public async Task ConnectAsync()
{
if (ConnectionInProgress) return;
ConnectionAttemptInformation = "";
ConnectionInProgress = true;
try
{
using (var tcpClient = new StreamSocket())
{
await tcpClient.ConnectAsync(
new Windows.Networking.HostName(HostName),
PortNumber,
SocketProtectionLevel.PlainSocket);
var localIp = tcpClient.Information.LocalAddress.DisplayName;
var remoteIp = tcpClient.Information.RemoteAddress.DisplayName;
ConnectionAttemptInformation = String.Format("Success, remote server contacted at IP address {0}",
remoteIp);
tcpClient.Dispose();
}
}
catch (Exception ex)
{
if (ex.HResult == -2147013895)
{
ConnectionAttemptInformation = "Error: No such host is known";
}
else if (ex.HResult == -2147014836)
{
ConnectionAttemptInformation = "Error: Timeout when connecting (check hostname and port)";
}
else
{
ConnectionAttemptInformation = "Error: Exception returned from network stack: " + ex.Message;
}
}
finally
{
ConnectionInProgress = false;
}
}
示例11: send_file_tcp
private async void send_file_tcp(String ipadd, int port)
{
try
{
_tcpclient = new StreamSocket();
await _tcpclient.ConnectAsync(new HostName(ipadd), port.ToString());
_datawriter = new DataWriter(_tcpclient.OutputStream);
StorageFolder folder = KnownFolders.PicturesLibrary;
StorageFile file = await folder.GetFileAsync(this.filepath);
IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();
_datareader = new DataReader(filestream);
while ((_length = await _datareader.LoadAsync(63 * 1024)) != 0)
{
_tosend = new byte[_length];
_datareader.ReadBytes(_tosend);
_datawriter.WriteBytes(_tosend);
await _datawriter.StoreAsync();
}
filestream.Dispose();
_datareader.Dispose();
_datawriter.Dispose();
_tcpclient.Dispose();
_message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
this.callback.on_file_received(_message, this.results);
this.main_view.text_to_logs(_message.Replace("\t", " "));
_stopwatch.Stop();
}
catch (Exception e)
{
append_error_tolog(e, _stopwatch.Elapsed, ipadd);
}
}
示例12: multicastSocket_MessageReceived
static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) {
try {
HostName remoteHostAddress = eventArguments.RemoteAddress;
uint len = eventArguments.GetDataReader().UnconsumedBufferLength;
string message = eventArguments.GetDataReader().ReadString(len).Trim();
int p = message.IndexOf(':');
if (p != -1) {
string serverLogToken = message.Substring(0, p);
int port = Int32.Parse(message.Substring(p + 1));
if (serverLogToken == logToken && port > 0 && port < 65535) {
Debug.WriteLine("[LOGGER] Found a Titanium log server: " + remoteHostAddress.DisplayName + ":" + port);
try {
tcpSocket = new StreamSocket();
tcpSocket.Control.KeepAlive = true;
await tcpSocket.ConnectAsync(remoteHostAddress, port.ToString());
tcpWriter = new DataWriter(tcpSocket.OutputStream);
// shutdown the multicast socket and start the tcp connection
multicastSocket.Dispose();
} catch {
if (tcpWriter != null) {
tcpWriter.Dispose();
tcpWriter = null;
}
if (tcpSocket != null) {
tcpSocket.Dispose();
tcpSocket = null;
}
}
}
}
} catch (Exception ex) {
if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
throw;
}
Debug.WriteLine(ex.ToString());
}
}
示例13: TransferPicture
private async void TransferPicture(StreamSocket socket)
{
// DataWriter erzeugen, um Byte-Umwandlung erledigen zu lassen...
var writer = new DataWriter(socket.OutputStream);
// Anzahl der zu übertragenden Bytes übertragen
writer.WriteInt32(App.PhotoBytesToShare.Length);
await writer.StoreAsync();
// Image-Bytes übertragen
writer.WriteBytes(App.PhotoBytesToShare);
await writer.StoreAsync();
await writer.FlushAsync();
UpdateStatus("Übertragung abgeschlossen.");
// Ressourcen freigeben
writer.Dispose();
socket.Dispose();
// Beenden der Annahme von Client-Verbindungen
_listener.Dispose();
}
示例14: sendMail
public async void sendMail(string strSendTo,string strContent , Boolean hasPicture)
{
HostName hostName = new HostName(hostIP);
StreamSocket socket = new StreamSocket();
List<string[]> storeList = new List<string[]>();
try
{
await socket.ConnectAsync(hostName, port);
}
catch (Exception exception)
{
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
}
StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
StorageFile pic = await folder.GetFileAsync("MyPainter.png");
IBuffer buffer = await FileIO.ReadBufferAsync(pic);
DataWriter writer = new DataWriter(socket.OutputStream);
writer.WriteUInt32(writer.MeasureString(strSendTo));
writer.WriteString(strSendTo);
writer.WriteUInt32(writer.MeasureString(strContent));
writer.WriteString(strContent);
if (hasPicture)
{
writer.WriteUInt32((uint)buffer.Length);
writer.WriteBuffer(buffer);
}
else
{
writer.WriteUInt32(0);
writer.WriteString("");
}
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
socket.Dispose();
}
示例15: OpenConnection
private void OpenConnection()
{
streamSocket = new StreamSocket();
HostName host = new HostName(Server);
CancellationTokenSource cts = new CancellationTokenSource();
try
{
cts.CancelAfter(timeout*1000);
streamSocket.Control.KeepAlive = true;
var task = streamSocket.ConnectAsync(host, Port.ToString()).AsTask(cts.Token);
task.Wait();
}
catch (TaskCanceledException)
{
// we timed out the connection
streamSocket.Dispose();
streamSocket = null;
throw new TimeoutException(Resources.Timeout);
}
}