Hi! Ich hab einen Server und einen Client geschrieben. Der Client sendet eine Zeichenkette an den Server, der Server sendet die Zeichenkette zurück an den Clienten. War ein Übungsprogramm zum Thema TCP/IP.
Allerdings funktioniert die Kommunikation nur auf dem localhost. Wenn ich also jemand anders den Server schicke und versuche dann auf dem PC auf den Server zu connecten funktioniert es nicht.
Ich bin mir sicher, das es am Client liegt. Hier der Code vom Client:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84:
| using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets;
namespace TCPClientClass { class TCPClientClass { static void Main(string[] args) { string Word = null; if ((args.Length < 1) || (args.Length > 3)) { throw new ArgumentException("Parameters: [<Server>] [<Port>]"); }
while (Word != "abcdefghijklmnopqrstuvwxyz") { Console.WriteLine("Was möchten Sie an den Server senden?"); Word = Console.ReadLine(); byte[] byteBuffer = Encoding.ASCII.GetBytes(Word);
string server = (args.Length == 1) ? args[0].ToString() : Dns.GetHostName(); int servPort = (args.Length == 2) ? Int32.Parse(args[1]) : 7;
TcpClient client = null; NetworkStream netStream = null;
try { client = new TcpClient(server, servPort);
Console.WriteLine("Connected to server... sending echo string");
netStream = client.GetStream();
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0; int bytesRcvd = 0; while (totalBytesRcvd < byteBuffer.Length) { if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0) { Console.WriteLine("Connection closed prematurely."); break; } totalBytesRcvd += bytesRcvd; }
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd, Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
} catch (Exception e) { Console.WriteLine(e.Message); } finally { netStream.Close(); client.Close(); } } } } } |
Moderiert von raziel: Code- durch C#-Tags ersetzt