基于Socket的点对点聊天程序
namespace 聊天程序{
public partial class Form1 : Form
{
private int listenport = 5555;
private TcpListener listener;
private Socket clientsocket;
private Thread processor;
private Thread clientservice;
private int serverport;
private NetworkStream ns;
private TcpClient tcpclient;
private string serveraddress;
public Form1()
{
InitializeComponent();
serverport = 5555;
processor = new Thread(new ThreadStart(StartListening));
processor.Start();
}
private void StartListening()
{
listener = new TcpListener(listenport);
listener.Start();
while (true)
{
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
private void ServiceClient()
{
Socket client = clientsocket;
Byte[] buffer = new Byte[1024];
client.Receive(buffer);
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer);
listBox1.Items.Add("对方:" + DateTime.Now.ToString() + ":" + clientcommand);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
client.Close();
clientservice.Abort();
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
serveraddress = txtIp.Text;
tcpclient = new TcpClient(serveraddress, serverport);
ns = tcpclient.GetStream();
listBox1.Items.Add("已方:" + DateTime.Now.ToString() + ":" + txtpe.Text);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(txtpe.Text.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
ns.Close();
tcpclient.Close();
}
catch (Exception ex)
{
MessageBox.Show("Could not connet to Server", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("你确定要退出?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
if (clientsocket != null)
clientsocket.Close();
if (clientservice != null)
clientservice.Abort();
listener.Stop();
if (processor != null)
processor.Abort();
}
else
e.Cancel = true;
}
}
}
这个是一个点对点的基于Socket的聊天程序,只能发英文字母,我想用StreamReader和StreamWriter改下可以改成可以用中文聊天,但是尝试过很多篇都失败了!求解下!