本文整理汇总了C#中System.Net.Sockets.Socket.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.Connect方法的具体用法?C# Socket.Connect怎么用?C# Socket.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BluetoothStream
public BluetoothStream(BluetoothDevice btdev)
{
socket = new Socket((AddressFamily)32, SocketType.Stream, (ProtocolType)3);
byte[] btAddress = btdev.Address;
try
{
BluetoothEndPoint btep = new BluetoothEndPoint(btAddress, guid_spp);
utils.ddump("connecting to " + btdev.AddressStr);
socket.Connect(btep);
utils.ddump("connected! Create networkstream...");
networkstream = new NetworkStream(socket, true);
utils.ddump("starting threads...");
thSend = new Thread(new ThreadStart(sendThread));
thSend.Name = "SendThread"; thSend.IsBackground = true;
thSend.Start();
utils.ddump("Thread started: " + thSend.Name + ", " + thSend.ManagedThreadId.ToString("x08"));
thRecv = new Thread(new ThreadStart(recvThread));
thRecv.Name = "RecvThread"; thRecv.IsBackground = true;
thRecv.Start();
utils.ddump("Thread started: " + thRecv.Name + ", " + thRecv.ManagedThreadId.ToString("x08"));
}
catch (Exception ex)
{
connected = false;
utils.ddump("BluetoothStream init failed with " + ex.Message);
}
}
示例2: GetResponseFromQuoteCache
private string GetResponseFromQuoteCache(string requestMessage)
{
var messageBytes = Encoding.ASCII.GetBytes(requestMessage);
try
{
// Open a new socket
var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(_quoteCacheHost, _quoteCachePort);
// Send request
int sentBytes = sender.Send(messageBytes);
Log.DebugFormat(CultureInfo.InvariantCulture,
"Sent {0} bytes over socket to \"{1}\" on port {2}.", sentBytes, _quoteCacheHost, _quoteCachePort);
// Wait for response
var responseBuffer = new byte[ResponseBufferSize];
int receivedBytes = sender.Receive(responseBuffer);
Log.DebugFormat(CultureInfo.InvariantCulture,
"Received {0} bytes over socket from \"{1}\" on port {2}.", receivedBytes, _quoteCacheHost, _quoteCachePort);
// Return response as string
return Encoding.ASCII.GetString(responseBuffer);
}
catch (Exception ex)
{
throw new QuoteException(String.Format(CultureInfo.InvariantCulture,
"Encountered an error while trying to connect to the quote cache at \"{0}\" on port {1}.",
_quoteCacheHost, _quoteCachePort), ex);
}
}
示例3: link
public bool link(int room){
if (socket != null) unlink();//断开之前的连接
socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket
string r =room.ToString();
try{
window.write("连接到"+r+"中...");
byte[] temp = Encoding.ASCII.GetBytes("{\"roomid\":"+r+ ",\"uid\":201510566613409}");//构造房间信息
socket.Connect("dm.live.bilibili.com", 788);//连接到弹幕服务器
//构造消息头
byte[] head = { 0x00, 0x00, 0x00, (byte)(0x31+r.Length), 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01 };
socket.Send(head);//发送消息头
socket.Send(temp);//发送请求正文——房间信息
socket.Send(re);//这个本来应该是用来获取人数的,但是长期不发送服务器会断开连接,这里是为了防止这样的情况发生
if (!flag)//检查读弹幕线程是否在工作
{
keeper = new Thread(keep_link);
keeper.IsBackground = true;
reader = new Thread(getdanmu);
reader.IsBackground = true;
reader.Start();
keeper.Start();
}
window.write("连接成功");
}
catch (InvalidCastException)
{
window.write("连接失败");
}
return true;
}
示例4: initializeConnection
public bool initializeConnection()
{
try
{
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
m_socket.SendTimeout = 5000;
m_socket.ReceiveTimeout = 5000;
m_frm.Print("Connecting to " + ECCServerIP + " at port " + ECCServerPort + " ...");
m_socket.Connect(ECCServerIP, Convert.ToInt32(ECCServerPort));
}
catch (Exception ex)
{
m_frm.Print("Error!Failed to connect to ECC server!" + ex.Message);
return false;
}
if (!Authenticate())
return false;
return true;
}
示例5: mysocket
public mysocket()
{
string line, ip;
int port;
string[] splits;
// config file read
StreamReader sr = new StreamReader("server_config");
line = sr.ReadLine();
splits = line.Split(' ');
ip = splits[2];
line = sr.ReadLine();
splits = line.Split(' ');
port = Convert.ToInt16(splits[2]);
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool reconnect = true;
while(reconnect){
try
{
s.Connect(ip, port);
handshake();
reconnect = false;
}
catch (System.Net.Sockets.SocketException)
{
Console.WriteLine("try to connect again");
}
}
}
示例6: Authorize
public static bool Authorize(string user, uint key)
{
try
{
Auth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
Auth.Connect(Configs.SERVER_IP, Configs.AUTH_PORT);
}
catch
{
Console.WriteLine("Failed to send client data to game server");
}
Auth.Send(System.Text.Encoding.ASCII.GetBytes("(A)" + user + "," + key));
Auth.Close();
}
catch (SocketException e)
{
Console.WriteLine("Exception Caught while connecting to game server: " + e.ErrorCode.ToString());
return false;
}
return true;
}
示例7: btnStartMulti_Click
private void btnStartMulti_Click(object sender, EventArgs e)
{
btnStopMulti_Click(this, EventArgs.Empty);
_isMultiStart = true;
var ipEndPoint = new IPEndPoint(IPAddress.Parse(txtMultiIp.Text), int.Parse(txtMultiPort.Text));
var threadCount = int.Parse(txtMultiThreadCount.Text);
for (var i = 0; i < threadCount; i++)
{
Task.Factory.StartNew(() =>
{
while (_isMultiStart)
{
var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_socketList.Add(socket);
socket.Connect(ipEndPoint);
socket.Close();
}
catch (Exception)
{
}
finally
{
_socketList.Remove(socket);
}
}
});
}
}
示例8: sendFile
public static void sendFile(string hostname, int port, string filepath) {
FileInfo file = new FileInfo(filepath);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(hostname, port);
int length = (int)file.Length;
using(FileStream reader = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None)) {
//socket.Send(BitConverter.GetBytes(length));
string fileName = Path.GetFileName(filepath);
Byte[] fn_bytes = Encoding.Default.GetBytes(fileName);
socket.Send(Methods.i2b(fn_bytes.Length));
socket.Send(fn_bytes);
socket.Send(Methods.i2b(length));
long send = 0L;
////Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
byte[] buffer = new byte[BufferSize];
int read, sent;
//断点发送 在这里判断设置reader.Position即可
while((read = reader.Read(buffer, 0, BufferSize)) !=0) {
sent = 0;
while((sent += socket.Send(buffer, sent, read, SocketFlags.None)) < read) {
send += (long)sent;
//Console.WriteLine("Sent " + send + "/" + length + ".");//进度
}
}
//Console.WriteLine("Send finish.");
}
}
示例9: SendCmdRequest
public bool SendCmdRequest(CmdRequest request)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect("127.0.0.1", Port);
using (NetworkStream stream = new NetworkStream(socket))
{
using (BsonWriter writer = new BsonWriter(stream))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, request);
writer.Flush();
writer.Close();
}
stream.Close();
}
}
catch(Exception ex)
{
Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex);
return false;
}
return true;
}
示例10: reConnect
public void reConnect()
{
clientSocket.Close();
clientSocket = null;
sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Threading.Thread tt = new System.Threading.Thread(delegate()
{
try
{
clientSocket.Connect(ip, port);
}
catch (Exception ee)
{
//MessageBox.Show(ee.Message + "\r\n From:" + this);
}
});
tt.Start();
}
catch (Exception e)
{
//MessageBox.Show(e.Message + "\r\n From:" + this);
}
}
示例11: GDBDebugger
public GDBDebugger()
{
string gdbHost = Application.Session.Properties["GDBDebugger.Host"];
int gdbPort = int.Parse(Application.Session.Properties["GDBDebugger.Port"]);
// Initialise locals
this.breakpoints = new List<Breakpoint>();
// Set the current architecture to the session one
this.CurrentArchitecture = Application.Session.Architecture;
// Connect to GDB stub
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Connect(gdbHost, gdbPort);
// Make empty initial register listing
this.Registers = new RegisterSet(new Register[0], new bool[0], new bool[0]);
// Create connector and begin debugging
this.connector = new GDBConnector(sock);
try
{
this.connector.EstablishConnection();
this.CurrentStatus = DebugStatus.Suspended;
this.connector.Paused += OnGDBPaused;
}
catch
{
this.CurrentStatus = DebugStatus.Disconnected;
this.connector.Dispose();
throw;
}
}
示例12: CSocket
public CSocket(IPEndPoint _endPoint, SocketPool _pool, SocketPoolProfile config)
{
socketConfig = config;
endpoint = _endPoint;
pool = _pool;
System.Net.Sockets.Socket _socket = new System.Net.Sockets.Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int)config.SendTimeout.TotalMilliseconds);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 24 * 3600 * 1000/*one day*/);//(int)config.ReceiveTimeout.TotalMilliseconds);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, !config.Nagle);
_socket.Connect(_endPoint);
socket = _socket;
this.inputStream = new BufferedStream(new NetworkStream(this.socket), config.BufferSize);
Thread th = new Thread(delegate() {
while (true)
{
try
{
Receive();
}
catch (Exception ex)
{
logger.Notice(ex.Message);
}
}
});
th.Start();
}
示例13: PostAction
private static bool PostAction(Proxy p, Server server, Action action)
{
var instance = p.Instance;
// if we can't issue any commands, bomb out
if (instance.AdminUser.IsNullOrEmpty() || instance.AdminPassword.IsNullOrEmpty()) return false;
var loginInfo = instance.AdminUser + ":" + instance.AdminPassword;
var haproxyUri = new Uri(instance.Url);
var requestBody = string.Format("s={0}&action={1}&b={2}", server.Name, action.ToString().ToLower(), p.Name);
var requestHeader = string.Format("POST {0} HTTP/1.1\r\nHost: {1}\r\nContent-Length: {2}\r\nAuthorization: Basic {3}\r\n\r\n",
haproxyUri.AbsolutePath, haproxyUri.Host, Encoding.GetEncoding("ISO-8859-1").GetBytes(requestBody).Length, Convert.ToBase64String(Encoding.Default.GetBytes(loginInfo)));
try
{
var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(haproxyUri.Host, haproxyUri.Port);
socket.Send(Encoding.UTF8.GetBytes(requestHeader + requestBody));
var responseBytes = new byte[socket.ReceiveBufferSize];
socket.Receive(responseBytes);
var response = Encoding.UTF8.GetString(responseBytes);
instance.PurgeCache();
return response.StartsWith("HTTP/1.0 303") || response.StartsWith("HTTP/1.1 303");
}
catch (Exception e)
{
Current.LogException(e);
return false;
}
}
示例14: CreateEndPoint
protected static Mono.Unix.UnixEndPoint CreateEndPoint (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint (
path);
if (System.IO.File.Exists (path)) {
System.Net.Sockets.Socket conn =
new System.Net.Sockets.Socket (
System.Net.Sockets.AddressFamily.Unix,
System.Net.Sockets.SocketType.Stream,
System.Net.Sockets.ProtocolType.IP);
try {
conn.Connect (ep);
conn.Close ();
throw new InvalidOperationException (
string.Format (CultureInfo.CurrentCulture,
Strings.UnixSocket_AlreadyExists,
path));
} catch (System.Net.Sockets.SocketException) {
}
System.IO.File.Delete (path);
}
return ep;
}
示例15: ConnectAndGetWebServerRequest
protected WebServerSocketRequest ConnectAndGetWebServerRequest(ushort requestId)
{
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ListenOn, ListenPort);
return new WebServerSocketRequest(sock, requestId);
}