我有一个客户端,它从用户那里获取IMPI(txtPrivateID.txt)
和IMPU(txtPublicID.txt)
两个ID进行注册,并将文本值发送到服务器。
IMPI
文本应该是128位长,它需要遵循
模式如' bob@ims.com'。 IMPU
也应该是128位长
它的模式是数字,如' 3556'。有关如何操作的任何提示?
客户端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace tcp_client
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void ConnectToServer()
{
string server_localip = GetLocalIP();
clientSocket.Connect(server_localip, 8888);
}
public void SendData(string dataTosend)
{
if (string.IsNullOrEmpty(dataTosend))
return;
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = new byte[33];
outStream= System.Text.Encoding.ASCII.GetBytes(dataTosend);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
public void CloseConnection()
{
clientSocket.Close();
}
public string ReceiveData()
{
StringBuilder message = new StringBuilder();
serverStream = clientSocket.GetStream();
serverStream.ReadTimeout = 100;
//the loop should continue until no dataavailable to read and message string is filled.
//if data is not available and message is empty then the loop should continue, until
//data is available and message is filled.
while (true)
{
if (serverStream.DataAvailable)
{
int read = serverStream.ReadByte();
if (read > 0)
message.Append((char)read);
else
break;
}
else if (message.ToString().Length > 0)
break;
}
return message.ToString();
}
public string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void btnConnect_Click(object sender, EventArgs e)
{
ConnectToServer();
btnConnect.Text = "Connected";
}
private void btnRegister_Click(object sender, EventArgs e)
{
string data = txtPrivateId.Text + ";" + txtPublicId.Text;
SendData(data);
string rec = null;
rec = ReceiveData();
txtReceive.Text = rec;
// CloseConnection();
}
}
}