因此在c#中制作了client-server-client tcp / ip应用程序,它们应该在不同网络中的两台计算机之间进行通信。
我遇到的问题很少,首先是我的服务器无法在我的公共ip上启动,说它在这种情况下无效。其次,我需要先按两次发送按钮,然后再将数据发送到服务器,然后服务器2更改数据,一个以字节为单位,另一个以char为单位。第三是如何使客户一直试图接收数据。客户之间是否应该全天候保持联系?我尝试使用计时器来检查是否要从服务器接收数据。
服务器代码
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 8080);
TcpClient client = default(TcpClient);
TcpClient client2 = default(TcpClient)
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch(Exception ex)
{
Console.WriteLine("Server failed to start... {0}",ex.ToString());
Console.Read();
}
while (true)
{
client = server.AcceptTcpClient(); /
byte[] receivedBuffer = new byte[1000];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer,0,receivedBuffer.Length);
StringBuilder message = new StringBuilder(); foreach (byte b in receivedBuffer)
{
if (b.Equals(126)
) //proveramo d {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
client2 = server.AcceptTcpClient();
byte[] receivedBuffer2 = new byte[1000];
NetworkStream stream2 = client2.GetStream();
stream2.Read(receivedBuffer2, 0, receivedBuffer2.Length);
StringBuilder message2 = new StringBuilder();
foreach (byte g in receivedBuffer2)
{
if (g.Equals(126))
{
break;
}
else
{
message2.Append(g);
}
}
stream2.Write(receivedBuffer, 0, receivedBuffer.Length);
stream.Write(receivedBuffer2,0,receivedBuffer2.Length);
Console.WriteLine(message2.ToString());
Console.WriteLine(message.ToString());
}
客户代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private int port = 8080;
private void submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("192.168.0.13",port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
long byteCount = Encoding.ASCII.GetByteCount(messagebox_TB.Text + 1); byte[] sentDataBytes = new byte[byteCount];
sentDataBytes = Encoding.ASCII.GetBytes(messagebox_TB.Text + "~");
NetworkStream stream = client.GetStream();
stream.Write(sentDataBytes,0,sentDataBytes.Length);
stream.Close();
client.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
long a = 0;
try
{
TcpClient client = new TcpClient("192.168.0.13", port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
NetworkStream stream = client.GetStream();
byte[] receviedBytes = new byte[100];
stream.Read(receviedBytes, 0, receviedBytes.Length);
StringBuilder
message = new StringBuilder();
foreach (byte b in receviedBytes) {
if (b.Equals(126)
) //proveramo {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
textBox1.Text = message.ToString();
client.Close();
stream.Close();
}
catch
{
a++;
}
}
}