局域网聊天问题(连接成功,却传不了信息)
程序代码:
//服务端 namespace Tcp_Server { public partial class Server_ : Form { public Server_() { InitializeComponent(); } string m_serverIP; int m_port; TcpListener m_Listener = null; IPAddress m_host; private void Server__Load(object sender, EventArgs e) { m_serverIP = txbServerName.Text;//IP地址 m_host = IPAddress.Parse(m_serverIP); m_port = int.Parse(txbPort.Text);//端口 m_Listener = new TcpListener(m_host, m_port); m_Listener.Start(); MessageBox.Show("开始侦听"); TcpClient m_client = m_Listener.AcceptTcpClient(); handle m_handle = new handle(); m_handle.ClientSocket = m_client; Thread m_clientthread = new Thread(new ThreadStart(m_handle.ResponseClient)); m_clientthread.Start(); txbShowIFMT.Text += m_handle.m_DataReturn; } } public class handle { byte[] EncodingASCII(string buf)//将数据转换为ASCII { byte[] data = Encoding.ASCII.GetBytes(buf); return data; } private TcpClient m_clientsocket; public string m_DataReturn, m_DataSend; byte[] data;//中间变量 public TcpClient ClientSocket { get { return m_clientsocket; } set { m_clientsocket = value; } }//m_clientsocket属性 public void ResponseClient() { StreamReader rs = new StreamReader(m_clientsocket.GetStream()); m_DataReturn = rs.ReadLine(); m_DataSend = "收到:" + m_DataReturn; NetworkStream ws = m_clientsocket.GetStream(); data = EncodingASCII(m_DataSend); ws.Write(data, 0, data.Length); } } }
程序代码:
//客户端 namespace Tcp_Client { public partial class Client_ : Form { public Client_() { InitializeComponent(); } static byte[] EncodingASCII(string buf)//将数据转换为ASCII { byte[] data = Encoding.ASCII.GetBytes(buf); return data; } string FriendServer, DataSend, DataReturn; int port; TcpClient m_client; byte[] data; StreamReader rs;//流 NetworkStream ws; private void Client__Load(object sender, EventArgs e) { FriendServer = txbFriend.Text; port = int.Parse(txbPort.Text);//端口 m_client = new TcpClient(); m_client.Connect(FriendServer, port); } private void btnSend_Click(object sender, EventArgs e) { rs = new StreamReader(m_client.GetStream()); ws = m_client.GetStream(); DataSend = txbSend.Text; data = EncodingASCII(DataSend); ws.Write(data, 0, data.Length); } } }
这样用流传递信息是这样的么?求大神指点!
[ 本帖最后由 yanglin_gdqy 于 2014-6-27 14:27 编辑 ]