Hola buenas, tengo un pequeño problema.
Quiero hacer un cliente al cual conecte a distintos servers simultaneamente y el comando que envie se envie a todos.
Hasta hay bien, el problema esta en que no consigo hacer varias conexiones a la ver solo una.
A ver si me podeis ayudar.
Gracias de antemano
aqui el codigo
Imports System.IO
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class Form1
Private oTCPStream As Net.Sockets.NetworkStream
Public Shared oTCP As New Net.Sockets.TcpClient()
Private bytWriting As [Byte]()
Private bytReading As Byte()
Private oHebras As Thread
Public Delegate Sub ParameterizedThreadStart(ByVal obj As String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtNameFile.ReadOnly = True
OpenFileDialog1.Filter = "File Txt |*.txt"
OpenFileDialog1.Title = "Open File"
OpenFileDialog1.Multiselect = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnArchivo.Click
ComboBox1.Items.Clear()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
txtNameFile.Text = OpenFileDialog1.FileName
End If
If Not Trim(txtNameFile.Text) = "" Then
Dim objReader As New StreamReader(txtNameFile.Text)
Dim sLine As String = ""
While sLine IsNot Nothing
sLine = objReader.ReadLine()
If sLine IsNot Nothing Then
ComboBox1.Items.Add(sLine)
End If
End While
objReader.Close()
End If
End Sub
Private Function ConnServ(ByRef VarIP) As Object
If Not VarIP = "" Then
Try
System.Threading.Thread.Sleep(1500)
oTCP.SendTimeout = 1500
oTCP.Connect(Trim(VarIP), "8000")
oTCPStream = oTCP.GetStream
WriteData(Trim(txtUser.Text) & vbCrLf)
System.Threading.Thread.Sleep(500)
WriteData(Trim(txtPassword.Text) & vbCrLf)
System.Threading.Thread.Sleep(500)
WriteData("Hello Serv" & vbCrLf)
System.Threading.Thread.Sleep(500)
' oTCPStream.Close()
' oTCP.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Return Nothing
End Function
Private Sub WriteData(ByVal sData As String)
bytWriting = System.Text.Encoding.ASCII.GetBytes(sData)
oTCPStream.Write(bytWriting, 0, bytWriting.Length)
End Sub
Private Sub btnConn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConn.Click
Dim I As Integer
Dim NewIP As String
For I = 0 To ComboBox1.Items.Count - 1
NewIP = (ComboBox1.Items(I).ToString)
Dim t As New Thread(DirectCast(Function() ConnServ(NewIP), ThreadStart))
t.Start()
Next
End Sub
End Class
No se puede conectar un socket cliente a varios servidores. Debes hacerte un array de sockets (o tcpClients) que conecten uno a cada servidor. Luego para mandarle los datos. Recorres ese arreglo enviando uno por uno
Exacto, un socket por conexión, jjejej Raul deja el empeño con los sockets, FlashNet usa TcpClient :P es lo mismo pero más arreglado.. :D
Claro, amenos de que desees controlar mejor la conexión, pero no creo que sea tu caso.
Un saludo!
Soy socket-Fan! JAJA.... es que desde que aprendi sockets (en vb6) lo uso de esa manera y me parece mas "comoda"
:P A mi también me gusta hacer las cosas así. xD es mas divertido. mas crudo :D
Me podias poner un ejemplo simple de conexion multiple con TcpClient?
y como se realizaria con un array?
Muchas gracias a los 2 por la ayuda
Cita de: D4N93R en 16 Marzo 2010, 14:23 PM
Exacto, un socket por conexión, jjejej Raul deja el empeño con los sockets, FlashNet usa TcpClient :P es lo mismo pero más arreglado.. :D
Claro, amenos de que desees controlar mejor la conexión, pero no creo que sea tu caso.
Un saludo!
Uhm, ahora no estoy en el equipo con VS y no puedo probar :( Alquien me puede ayudar aki , raul! jaja
acabo de reformatear y tampoco tengo el vs, asi que pondre algo de C# con pseudo codigo JAJA XD
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Net;
namespace MuestraClienteMultiple{
class program {
struct Conexion {
byte[] buffer;
TcpClient client;
string host;
}
static int main() {
string[] hosts = { "google.com", "www.raul338.com.ar" }; // direcciones servidor
List<Conexion> conexiones = new List<Conexion>(hosts.Length); // Lista del mismo tamaño de las direcciones
foreach (string s in hosts) {
Conexion conex;
conex.host = s;
conex.buffer = new Byte[2048]; // 2 Mb de buffer
conex.client = new TcpClient(); // Direccion en el puerto 80
conexiones.Add(conex);
conex.client Connect(s, 80);
if (conex.client.Connected) {
StreamReader sr = new StreamReader(conex.client.GetStream());
Console.WriteLine(sr.ReadToEnd());
}
conex.Close();
} // foreach
}
}// class program
}// namespace
Deberia funcionar, .... es un ejemplo basico inventado al vuelo. Te devuelve las salidas HTML de google y de mi pagina web :P
Muchisimas gracias a los 2, le voy a echar un vistazo.
Se agradece vuestro interes
:-)
Excelente, Y eso que esta echo a lo rápido, pero quedo muy bien, voy a modificarlo con tu permiso.
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Net;
namespace MuestraClienteMultiple{
class program {
public class Conexion {
byte[] buffer;
TcpClient client;
string host;
public Conexion(string hostname, int bufferSize){
host =hostname;
buffer = new Byte[bufferSize];
}
public string GetData(){
string result=String.Empty;
try{
client Connect(s, 80);
if (client.Connected) {
StreamReader sr = new StreamReader(client.GetStream());
result= sr.ReadToEnd());
}
}
finally{
conex.Close();
}
return result;
}
}
static int main() {
string[] hosts = { "google.com", "www.raul338.com.ar" }; // direcciones servidor
List<Conexion> conexiones = new List<Conexion>(hosts.Length); // Lista del mismo tamaño de las direcciones
foreach (string s in hosts) {
Conexion conex = new Conexion(x, 2048);
//conex.buffer = new Byte[2048]; // 2 Mb de buffer
//conex.client = new TcpClient(); // Direccion en el puerto 80
conexiones.Add(conex);
Console.WriteLine(conex.GetData());
} // foreach
}
}// class program
}// namespace
Cita de: D4N93R en 17 Marzo 2010, 15:31 PM
Excelente, Y eso que esta echo a lo rápido, pero quedo muy bien, voy a modificarlo con tu permiso.
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Net; // Double Imports xD XD - OWNED
namespace MuestraClienteMultiple{
class program {
public class Conexion {
byte[] buffer;
TcpClient client;
string host;
public Conexion(string hostname, int bufferSize){
host =hostname;
buffer = new Byte[bufferSize];
}
public string GetData(){
string result=String.Empty;
try{
client.Connect(s, 80); // Falto un punto, punto primordial (?
if (client.Connected) {
StreamReader sr = new StreamReader(client.GetStream());
result= sr.ReadToEnd());
}
}
finally{
conex.Close();
}
return result;
}
}
static int main() {
string[] hosts = { "google.com", "www.raul338.com.ar" }; // direcciones servidor
List<Conexion> conexiones = new List<Conexion>(hosts.Length); // Lista del mismo tamaño de las direcciones
foreach (string s in hosts) {
Conexion conex = new Conexion(x, 2048);
//conex.buffer = new Byte[2048]; // 2 Mb de buffer
//conex.client = new TcpClient(); // Direccion en el puerto 80
conexiones.Add(conex);
Console.WriteLine(conex.GetData());
} // foreach
}
}// class program
}// namespace
Esta bien, salvo por eso, de donde aparece la variable S :xD XD, tiene que ser "host" ;)
flashnet, tambien deberias a aprender a manejarlos asincronicamente(con delegados) asi no se te tilda la aplicacion mientras pide los datos ;-) (tipico caso de un socket intentando conectar a unhost inexistente, esperar 30 segundos hasta que te diga "no se pudo conectar" :¬¬)
Ups :silbar:
Hey, como hiciste para resaltar esa linea :(
[ code=(lenguaje),(nº de linea a resaltar) ] :P
Cita de: D4N93R en 17 Marzo 2010, 18:14 PM
Ups :silbar:
Hey, como hiciste para resaltar esa linea :(
en el geshi despues de poner el lenguaje pones la linea que queres resaltar...por ejemplo:
[ code=csharp,2]
eso resalta la linea 2 del codigo...
saludos.
PD: posteamos juntos..
Gracias nuevamente a los dos, ahora mismo me voy a poner a probar.
El tema de delegates tambien lo mirare y ya os contare mis progresos.
Gracias
Gracias a ambos, jeje si, hicieron el post al mismo tiempo :P