我做了一個tcp/ip聊天窗口窗體應用程序,它工作得很好,但我想讓應用程序自動發送文本我不希望用戶點擊發送按鈕就像一個活流!窗體應用程序發送字符串
我正在使用異步連接。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Chat
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textBox1.Text = GetLocalIP();//this is where the application is running IP address
//textBox5.Text = GetLocalIP();
}
private 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"; //here we put the android device's IP
}
private void MessageCallBack(IAsyncResult aResult)
{
try {
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if(size>0)
{
byte[] receivedData = new byte[1464];
receivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(receivedData);
//b3deen bntba3 el msg bs b7aletna bdna n5li el touch active.
listBox1.Items.Add("Sender:" + receivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//binding the message
epLocal = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("80"));
sck.Bind(epLocal);
//hoon el address ta3 el mobile
epRemote = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("81"));//texbox5 bn7at el ip ta3 el android wl txt el tani ta3 le port
//hoon bn3ml connect network
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
button1.Text = "Connected";
button1.Enabled = false;
button2.Enabled = true;
textBox3.Focus();
//trying to live sending
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textBox3.Text);
sck.Send(msg);
listBox1.Items.Add("YOU:" + textBox3.Text);
}catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
// Close();
}
}
}
發表一些代碼。你想發送文本作爲用戶類型? – Abhishek
是的是的:D我會添加代碼只是一秒@Abhishek –