i need an advice about winforms
basically, i made an application on the console that sends and receives i开发者_如何学JAVAnformation. it works like a chat (it does work, like i chat, i checked).
now what i did here. i transfered some of the code to a winform, and i struggle to understand how can i make the output received (readLine) be printed on the label and input to be sent by the textfield!!
could you direct me and tell me where my mistakes, and how can i make the chat work?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
TcpClient connection;
StreamReader sr;
StreamWriter sw;
public Form1()
{
InitializeComponent();
}
private void connectServer()
{
connection = new TcpClient("127.0.0.1", 5000);
sr = new StreamReader(connection.GetStream());
sw = new StreamWriter(connection.GetStream());
}
void button_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
sw.WriteLine(richTextBox1.Text);
sw.Flush();
}
private void label1_Click(object sender, EventArgs e)
{
label1.Text = sr.ReadLine();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
So...
you can chat from where to where? same machine, same network, internet?
You need to create a service to handle the conversation, a global point for all chats, that gets the message and saves it.
Then you need to, from each client, hook up to that global point and create a "room" and attach the client as an observable, every time there is a new message in that "room", all observable clients will be warn of incoming message and update their textbox.
If you want to avoid a "global point" you can use sockets, though, it might not work if the client is somewhere behind a NAT.
here is a full application in WCF
http://www.codeproject.com/KB/WCF/WCFWPFChat.aspx
精彩评论