本文整理汇总了C#中System.Net.Sockets.TcpClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.Connect方法的具体用法?C# TcpClient.Connect怎么用?C# TcpClient.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpClient
的用法示例。
在下文中一共展示了TcpClient.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
public void Start(string[] args)
{
registry = new Registry();
if (!registry.Register(this))
{
Console.WriteLine("Error registering service.");
return;
}
Console.WriteLine("Registered service.");
try
{
TcpClient tcpclient = new TcpClient();
if (args.Count() != 2)
throw new Exception("Argument must contain a publishing ip and port. call with: 127.0.0.1 12345");
tcpclient.Connect(args[0], Int32.Parse(args[1]));
StreamReader sr = new StreamReader(tcpclient.GetStream());
string data;
while ((data = sr.ReadLine()) != null)
{
Console.WriteLine("Raw data: " + data);
if (RawAisData != null)
RawAisData(data);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message + e.StackTrace);
Console.WriteLine("Press enter");
Console.ReadLine();
}
}
示例2: Connect
public void Connect()
{
if(_stream == null)
{
_client = new TcpClient();
if (_config.host != null)
_client.Connect(_config.host, _config.port);
else
_client.Connect(new IPEndPoint(IPAddress.Parse(_config.ip), _config.port));
_stream = _client.GetStream();
}
}
示例3: Connect
public Boolean Connect()
{
try
{
if (recvThread != null)
recvThread.Abort();
}
catch (Exception ex)
{
}
tcpClient = new TcpClient();
try
{
tcpClient.Connect(ServerIP, Port);
tcpClient.Client.Blocking = true;
//tcpClient.Client.ReceiveTimeout = 1000;
tcpClient.Client.LingerState = new LingerOption(true, 0);
recvThread = new Thread(new ThreadStart(RecvRequestFromClient));
recvThread.Start();
IsConnected = true;
return true;
}
catch (SocketException ex)
{
if (OnSocketError != null)
OnSocketError(0, new SocketEventArgs((int)ex.ErrorCode, ex.Message));
}
return false;
}
示例4: ConnectRemote
private TcpClient ConnectRemote(IPEndPoint ipEndPoint)
{
TcpClient client = new TcpClient();
try
{
client.Connect(ipEndPoint);
}
catch (SocketException socketException)
{
if (socketException.SocketErrorCode == SocketError.ConnectionRefused)
{
throw new ProducerException("服务端拒绝连接",
socketException.InnerException ?? socketException);
}
if (socketException.SocketErrorCode == SocketError.HostDown)
{
throw new ProducerException("订阅者服务端尚未启动",
socketException.InnerException ?? socketException);
}
if (socketException.SocketErrorCode == SocketError.TimedOut)
{
throw new ProducerException("网络超时",
socketException.InnerException ?? socketException);
}
throw new ProducerException("未知错误",
socketException.InnerException ?? socketException);
}
catch (Exception e)
{
throw new ProducerException("未知错误", e.InnerException ?? e);
}
return client;
}
示例5: ListenerSocket
/// <summary>
/// Constructor
/// </summary>
public ListenerSocket()
{
// Init
loadBalancerSocket = new TcpClient();
// Connect to the loadbalancer
Console.Write("Enter the loadbalancer ip: "); // Prompt
loadBalancerSocket.Connect(IPAddress.Parse(Console.ReadLine()), int.Parse(Server.Properties.Resources.LoadBalancerPort));
Logger.ShowMessage(
String.Format("Connected to loadbalancer on: {0}:{1} and {2}:{3}",
((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Address,
((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Port,
((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Address,
((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Port
)
);
Clients = new List<TcpClient>();
messageHandler = new MessageHandler();
// Make the socket listener and thread
Random randomPort = new Random();
listenerSocket = new TcpListener(IPAddress.Any, randomPort.Next(8900, 9000));
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
sendServerPort(loadBalancerSocket, ((IPEndPoint)listenerSocket.LocalEndpoint).Port);
Logger.ShowMessage("Listener initialized.");
Logger.ShowMessage("Listening on: " + ((IPEndPoint)listenerSocket.LocalEndpoint).Address + ":" + ((IPEndPoint)listenerSocket.LocalEndpoint).Port);
// Define the handlers.
PacketManager.DefineOpcodeHandlers();
}
示例6: Test
public TestResultBase Test(Options o)
{
var p = new Uri(o.Url);
var res = new GenericTestResult
{
ShortDescription = "TCP connection port " + p.Port,
Status = TestResult.OK
};
try
{
var client = new TcpClient();
client.Connect(p.DnsSafeHost, p.Port);
res.Status = TestResult.OK;
client.Close();
}
catch (Exception ex)
{
res.Status = TestResult.FAIL;
res.CauseOfFailure = ex.Message;
}
return res;
}
示例7: Main
static void Main(string[] args)
{
var port = Convert.ToInt32(args[0]);
var timeout = Convert.ToInt32(args[1]);
var buffer = new byte[12];
client = new TcpClient();
client.Connect(IPAddress.Loopback, port);
client.Client.BeginReceive(termBuffer, 0, 1, SocketFlags.None,
inputClient_DataReceived, null);
Console.WriteLine("Connected to Nexus at 127.0.0.1:{0}", port);
Wiimotes.ButtonClicked += Button;
int numConnnected = Wiimotes.Connect(timeout);
if (numConnnected > 0) {
Console.WriteLine("{0} wiimote(s) found", numConnnected);
CopyInt(ref buffer, 1, 0);
CopyInt(ref buffer, numConnnected, 4);
CopyInt(ref buffer, 0, 8);
client.Client.Send(buffer);
Wiimotes.Poll();
}
else {
CopyInt(ref buffer, 1, 0);
CopyInt(ref buffer, 0, 4);
CopyInt(ref buffer, 0, 8);
client.Client.Send(buffer);
Console.WriteLine("No Wiimotes found");
}
}
示例8: talk
public bool talk()
{
try
{
if (null != sendPro)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)),
int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort)));
NetworkStream ns = client.GetStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ns, sendPro);
reseivePro = (Protocol)formatter.Deserialize(ns);
client.Close();
}
else
{
return false;
}
return true;
}
catch (Exception)
{
return false;
}
}
示例9: ConnectToServer
public void ConnectToServer(string msg)
{
try
{
_client = new TcpClient();
_client.Connect(_endPoint);
byte[] bytes = Encoding.ASCII.GetBytes(msg);
using (NetworkStream ns = _client.GetStream())
{
Trace.WriteLine("Sending message to server: " + msg);
ns.Write(bytes, 0, bytes.Length);
bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string serverResponse = Encoding.ASCII.GetString(bytes, 0, bytesRead);
Trace.WriteLine("Server said: " + serverResponse);
}
}
catch (SocketException se)
{
Trace.WriteLine("There was an error talking to the server: " + se.ToString());
}
finally
{
Dispose();
}
}
示例10: StartClient
public void StartClient()
{
TcpClient tc = new TcpClient();
tc.Connect("localhost", 9988);
NetworkStream ns = tc.GetStream();
List<byte> dataList = new List<byte>();
//Node Id
dataList.AddRange(BitConverter.GetBytes(1001));
//Node Name
dataList.AddRange(Encoding.ASCII.GetBytes("NK1001"));
//Temperature
dataList.AddRange(BitConverter.GetBytes((short)37));
//Longitude
dataList.AddRange(BitConverter.GetBytes((double)121.29));
dataList.Add(0);
byte[] data = dataList.ToArray();
Console.WriteLine("Press <Enter> to send");
while (Console.ReadLine() != null)
{
ns.Write(data, 0, data.Length);
}
}
示例11: Connect
public Boolean Connect(String ip, int port)
{
try
{
TcpClient = new System.Net.Sockets.TcpClient();
TcpClient.ReceiveTimeout = 5000;
TcpClient.SendTimeout = 5000;
TcpClient.Connect(ip, port);
Ns = TcpClient.GetStream();
Bw = new BinaryWriter(TcpClient.GetStream());
Br = new BinaryReader(TcpClient.GetStream());
IsConnected = true;
}
catch (Exception e)
{
IsConnected = false;
Log.Cl(e.Message);
return false;
}
ReceptionThread = new Thread(new ThreadStart(Run));
ReceptionThread.IsBackground = true;
ReceptionThread.Start();
return true;
}
示例12: Connect
public void Connect(string ip, int port = 8085)
{
_ip = ip;
_port = port;
_tcp = new TcpClient();
_tcp.Connect(_ip, _port);
_ns = _tcp.GetStream();
ThreadPool.QueueUserWorkItem((x)=> {
while(_tcp.Connected)
{
try
{
if (_ns.DataAvailable)
{
byte[] buffer = new byte[4096];
int bytesread = _ns.Read(buffer, 0, buffer.Length);
Array.Resize(ref buffer, bytesread);
string msg = Encoding.UTF8.GetString(buffer);
HandlePacket(msg);
}
}
catch { }
}
_ns.Close();
_ns.Dispose();
_tcp.Close();
Thread.CurrentThread.Abort();
});
}
示例13: Parse
private void Parse()
{
TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client
//bool flag = sslstream.IsAuthenticated; // check flag
System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command
sw.Flush(); // sent to server
sw.WriteLine("PASS utybfkmyjcnm321");
sw.Flush();
sw.WriteLine("RETR 5");
sw.Flush();
sw.WriteLine("Quit "); // close the connection
sw.Flush();
string str = string.Empty;
string strTemp = string.Empty;
while ((strTemp = reader.ReadLine()) != null)
{
if (".".Equals(strTemp))
{
break;
}
if (strTemp.IndexOf("-ERR") != -1)
{
break;
}
str += strTemp;
}
MessageBox.Show(str);
}
示例14: Connect
/// <summary>
/// Connect TCP socket to a server.
/// </summary>
/// <param name="serverAddr">IP or hostname of server.</param>
/// <param name="port">Port that TCP should use.</param>
/// <returns>True if connection is successful otherwise false</returns>
internal bool Connect(string serverAddr, int port)
{
try
{
IPAddress[] serverIP = Dns.GetHostAddresses(serverAddr);
if (serverIP.Length <= 0)
{
mErrorString = "Error looking up host name";
return false;
}
mTCPClient = new TcpClient();
mTCPClient.Connect(serverIP[0], port);
// Disable Nagle's algorithm
mTCPClient.NoDelay = true;
}
catch (SocketException e)
{
mErrorString = e.Message;
mErrorCode = e.SocketErrorCode;
if (mTCPClient != null)
{
mTCPClient.Close();
}
return false;
}
return true;
}
示例15: Button3_Click
private void Button3_Click(object sender, RoutedEventArgs e)
{
try
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
// load spim-generated data from embedded resource file
const string spimDataName = "Simulation.Repressilator.txt";
using (Stream spimStream = executingAssembly.GetManifestResourceStream(spimDataName))
{
using (StreamReader r = new StreamReader(spimStream))
{
string line = r.ReadLine();
while (!r.EndOfStream)
{
TcpClient client = new TcpClient();
IPAddress ip1 = IPAddress.Parse(textBox1.Text.Trim());//{ 111, 186, 100, 46 }
client.Connect(ip1, 8500);
Stream streamToServer = client.GetStream(); // 获取连接至远程的流
line = r.ReadLine();
byte[] buffer = Encoding.Unicode.GetBytes(line);
streamToServer.Write(buffer, 0, buffer.Length);
streamToServer.Flush();
streamToServer.Close();
client.Close();
Thread.Sleep(10); // Long-long time for computations...
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}