using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace form1
{
public partial class Form1 : Form
{
TcpClient client;
NetworkStream stream;
Thread th;
public Form1()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
ipBox.Text = "127.0.0.1";
portBox.Text = "2000";
username.Text = "clinet";
IPHostEntry iph = new IPHostEntry();
iph = Dns.GetHostByName(Dns.GetHostName());
string ddd = iph.AddressList[0].ToString();
ipBox.Text = ddd; //获取本机的IP地址
label5.Text = ddd;
}
private void button1_Click(object sender, EventArgs e)
{
//需要验证连接是否成功!!!!!!!!!!!!!
Byte[] data = Encoding.Default.GetBytes(username.Text+" "+DateTime.Now.ToString() + "\r\n" + SendBox.Text);
stream.Write(data, 0, data.Length);
informationBox.Text = informationBox.Text + "\r\n" + username.Text + " " + DateTime.Now.ToString() + "\r\n" + SendBox.Text;
SendBox.Text = "";
this.SendBox.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
Byte[] data = Encoding.Default.GetBytes("ClientClose");
stream.Write(data, 0, data.Length);
th.Abort();
stream.Close();
client.Close();
}
catch (Exception) { }
Close();
}
private void button3_Click(object sender, EventArgs e)
{
if (username.Text != "" && ipBox.Text != "" && portBox.Text != "")
{
username.Enabled = false;
//开始连接
try
{
int port = 2000;
string host = ipBox.Text;
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port); //定义IP和端口
client = new TcpClient(host,port);
stream = client.GetStream(); //连接
informationBox.Text = informationBox.Text + "开始连接....";
th = new Thread(new ThreadStart(readData)); //调用接受进程
th.Start();
Byte[] data = Encoding.Default.GetBytes("连接成功!");
sendbutton.Enabled = true;
stream.Write(data, 0, data.Length);
}
catch (ArgumentNullException d)
{
informationBox.Text = informationBox.Text + "\r\n" + d.Message;
}
catch (SocketException d)
{
informationBox.Text = informationBox.Text + "\r\n" + d.Message;
}
}
else
{
MessageBox.Show("请填写完整的连接信息和昵称");
}
}
private void button4_Click(object sender, EventArgs e)
{
username.Enabled = true;
}
public void readData()
{
while (true)
{
byte[] data = new byte[256];
string str = string.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
str = Encoding.Default.GetString(data, 0, bytes);
if (str == "ServerClose")
{
sendbutton.Enabled = false;
SendBox.Enabled = false;
MessageBox.Show("服务器已经关闭,请关闭客户端");
stream.Close();
client.Close();
break;
}
else
informationBox.AppendText("\r\n"+ str);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
C#利用socket实现的一对一聊天工具源代码
5星 · 超过95%的资源 需积分: 50 120 浏览量
2008-10-31
19:47:16
上传
评论 1
收藏 249KB RAR 举报
sss15
- 粉丝: 0
- 资源: 3
- 1
- 2
- 3
前往页