在IP上发送消息 [英] Send a message on IP
问题描述
我想创建一个简单的Windows窗体应用程序,其中有一个可以正常工作的客户端.服务器的问题是我真正想要的是一个简单的文本框,在其中我将键入ipaddress和一个按钮,如果我单击该按钮,应在我在文本框中键入的ip上发送一条消息.请帮助我与服务器.感谢adv!
但是您能用我想要异步接收数据的这段代码来帮助我吗?我该如何修改这段代码?
I want to create a simple Windows form application in which i have a client which works properly. the problem is with the server What i exactly want is there will be a simple textbox in which i will type ipaddress and a button which if i click should send a message on the ip that i typed in textbox.. I have client. Please help me with the server. Thanx in adv!!
but can u help me with this code i want to asynchronously receive data how can i modify this code?
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8000);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
DialogResult m = MessageBox.Show("You Have received a Message!");
if (m == DialogResult.OK)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
label1.Text = "Message: " + stringData;
sock.Close();
[/EDIT]
[/EDIT]
推荐答案
在本文以及Google可以为您找到的更广泛的网络上,都有很多套接字编程的示例.
There are lots of samples of socket programming both here in the Articles and on the wider net which Google will find for you.
您可以尝试使用此客户端和服务器代码:
网络文件sender.cs
you can try this client and server code:
Network File sender.cs
public partial class Form1 : Form
{
// The TCP client will connect to the server using an IP and a port
TcpClient tcpClient;
// The file stream will read bytes from the local file you are sending
FileStream fstFile;
// The network stream will send bytes to the server application
NetworkStream strRemote;
public Form1()
{
InitializeComponent();
}
private void ConnectToServer(string ServerIP, int ServerPort)
{
// Create a new instance of a TCP client
tcpClient = new TcpClient();
try
{
// Connect the TCP client to the specified IP and port
tcpClient.Connect(ServerIP, ServerPort);
txtLog.Text += "Successfully connected to server\r\n";
}
catch (Exception exMessage)
{
// Display any possible error
txtLog.Text += exMessage.Message;
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
// Call the ConnectToServer method and pass the parameters entered by the user
ConnectToServer(txtServer.Text, Convert.ToInt32(txtPort.Text));
}
private void btnSend_Click(object sender, EventArgs e)
{
// If tclClient is not connected, try a connection
if (tcpClient.Connected == false)
{
// Call the ConnectToServer method and pass the parameters entered by the user
ConnectToServer(txtServer.Text, Convert.ToInt32(txtPort.Text));
}
// Prompt the user for opening a file
if (openFile.ShowDialog() == DialogResult.OK)
{
txtLog.Text += "Sending file information\r\n";
// Get a stream connected to the server
strRemote = tcpClient.GetStream();
byte[] byteSend = new byte[tcpClient.ReceiveBufferSize];
// The file stream will read bytes from the file that the user has chosen
fstFile = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);
// Read the file as binary
BinaryReader binFile = new BinaryReader(fstFile);
// Get information about the opened file
FileInfo fInfo = new FileInfo(openFile.FileName);
// Get and store the file name
string FileName = fInfo.Name;
// Store the file name as a sequence of bytes
byte[] ByteFileName = new byte[2048];
ByteFileName = System.Text.Encoding.ASCII.GetBytes(FileName.ToCharArray());
// Write the sequence of bytes (the file name) to the network stream
strRemote.Write(ByteFileName, 0, ByteFileName.Length);
// Get and store the file size
long FileSize = fInfo.Length;
// Store the file size as a sequence of bytes
byte[] ByteFileSize = new byte[2048];
ByteFileSize = System.Text.Encoding.ASCII.GetBytes(FileSize.ToString().ToCharArray());
// Write the sequence of bytes (the file size) to the network stream
strRemote.Write(ByteFileSize, 0, ByteFileSize.Length);
txtLog.Text += "Sending the file " + FileName + " (" + FileSize + " bytes)\r\n";
// Reset the number of read bytes
int bytesSize = 0;
// Define the buffer size
byte[] downBuffer = new byte[2048];
// Loop through the file stream of the local file
while ((bytesSize = fstFile.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
// Write the data that composes the file to the network stream
strRemote.Write(downBuffer, 0, bytesSize);
}
// Update the log textbox and close the connections and streams
txtLog.Text += "File sent. Closing streams and connections.\r\n";
tcpClient.Close();
strRemote.Close();
fstFile.Close();
txtLog.Text += "Streams and connections are now closed.\r\n";
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
// Close connections and streams and update the log textbox
tcpClient.Close();
strRemote.Close();
fstFile.Close();
txtLog.Text += "Disconnected from server.\r\n";
}
}
网络文件Receiver.cs
Network File Receiver.cs
public partial class Form1 : Form
{
// The thread in which the file will be received
private Thread thrDownload;
// The stream for writing the file to the hard-drive
private Stream strLocal;
// The network stream that receives the file
private NetworkStream strRemote;
// The TCP listener that will listen for connections
private TcpListener tlsServer;
// Delegate for updating the logging textbox
private delegate void UpdateStatusCallback(string StatusMessage);
// Delegate for updating the progressbar
private delegate void UpdateProgressCallback(Int64 BytesRead, Int64 TotalBytes);
// For storing the progress in percentages
private static int PercentProgress;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
thrDownload = new Thread(StartReceiving);
thrDownload.Start();
}
private void StartReceiving()
{
// There are many lines in here that can cause an exception
try
{
// Get the hostname of the current computer (the server)
string hstServer = Dns.GetHostName();
// Get the IP of the first network device, however this can prove unreliable on certain configurations
IPAddress ipaLocal = Dns.GetHostEntry(hstServer).AddressList[0];
// If the TCP listener object was not created before, create it
if (tlsServer == null)
{
// Create the TCP listener object using the IP of the server and the specified port
tlsServer = new TcpListener(ipaLocal, Convert.ToInt32(txtPort.Text));
}
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Starting the server...\r\n" });
// Start the TCP listener and listen for connections
tlsServer.Start();
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has started. Please connect the client to " + ipaLocal.ToString() + "\r\n" });
// Accept a pending connection
TcpClient tclServer = tlsServer.AcceptTcpClient();
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has accepted the client\r\n" });
// Receive the stream and store it in a NetworkStream object
strRemote = tclServer.GetStream();
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has received the stream\r\n" });
// For holding the number of bytes we are reading at one time from the stream
int bytesSize = 0;
// The buffer that holds the data received from the client
byte[] downBuffer = new byte[2048];
// Read the first buffer (2048 bytes) from the stream - which represents the file name
bytesSize = strRemote.Read(downBuffer, 0, 2048);
// Convert the stream to string and store the file name
string FileName = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);
// Set the file stream to the path C:\ plus the name of the file that was on the sender''s computer
strLocal = new FileStream(@"C:\raj\" + FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
// The buffer that holds the data received from the client
downBuffer = new byte[2048];
// Read the next buffer (2048 bytes) from the stream - which represents the file size
bytesSize = strRemote.Read(downBuffer, 0, 2048);
// Convert the file size from bytes to string and then to long (Int64)
long FileSize = Convert.ToInt64(System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize));
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Receiving file " + FileName + " (" + FileSize + " bytes)\r\n" });
// The buffer size for receiving the file
downBuffer = new byte[2048];
// From now on we read everything that''s in the stream''s buffer because the file content has started
while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
// Write the data to the local file stream
strLocal.Write(downBuffer, 0, bytesSize);
// Update the progressbar by passing the file size and how much we downloaded so far to UpdateProgress()
this.Invoke(new UpdateProgressCallback(this.UpdateProgress), new object[] { strLocal.Length, FileSize });
}
// When this point is reached, the file has been received and stored successfuly
}
finally
{
// This part of the method will fire no matter wether an error occured in the above code or not
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The file was received. Closing streams.\r\n" });
// Close the streams
strLocal.Close();
strRemote.Close();
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Streams are now closed.\r\n" });
// Start the server (TCP listener) all over again
StartReceiving();
}
}
private void UpdateStatus(string StatusMessage)
{
// Append the status to the log textbox text
txtLog.Text += StatusMessage;
}
private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
{
if (TotalBytes > 0)
{
// Calculate the download progress in percentages
PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
// Make progress on the progress bar
prgDownload.Value = PercentProgress;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
strLocal.Close();
strRemote.Close();
txtLog.Text += "Streams are now closed.\r\n";
}
private void btnStop_Click_1(object sender, EventArgs e)
{
}
}
这篇关于在IP上发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!