|
就是那种木有服务器的,两个人直接通过IP进行链接然后对话,我尝试着写了一个,但貌似有点问题,望指教。代码贴在下面:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace 游戏1
{
public partial class Formjiao : Form
{
private TcpListener lisp1;
private Thread td;
private static string xin = "";
public Formjiao()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try {
TcpClient client = new TcpClient(Formtalk.ipto,888);
string mess = " "+Form3.yhm + DateTime.Now.ToString() + '\n' + richTextBox2.Text + "\n";
NetworkStream netsm = client.GetStream();
StreamWriter wsm = new StreamWriter(netsm,Encoding.Default);
wsm.Write(mess);
wsm.Flush();
wsm.Close();
client.Close();
richTextBox1.AppendText(mess);
richTextBox1.ScrollToCaret();
richTextBox2.Text = "";
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
private void Formjiao_Load(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(this.StartListen));
td.Start();
timer1.Start();
}
private void StartListen() {
// richTextBox2.Text = "";
IPHostEntry host = Dns.GetHostEntry(Formtalk.ipto);
IPAddress MyIP = host.AddressList[0];
lisp1 = new TcpListener(MyIP,888);
lisp1.Start();
while (true) {
TcpClient tct = lisp1.AcceptTcpClient();
NetworkStream mstm = tct.GetStream();
byte[] mb=new byte[1024];
int i = mstm.Read(mb,0,mb.Length);
xin = Encoding.Default.GetString(mb,0,i);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (xin != "")
{
richTextBox1.AppendText(xin);
richTextBox1.ScrollToCaret();
xin = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
richTextBox2.Text = "";
}
}
}
|
|