//Server Code
using System;
using System.Net.Sockets;
using System.IO ;
public class Echoserver
{
public static void Main()
{
//TcpListener is listening on the given port... {
TcpListener tcpListener = new TcpListener(1234);
tcpListener.Start();
Console.WriteLine("Server Started") ;
Socket socketForClient = tcpListener.AcceptSocket();
try
{
if (socketForClient.Connected)
{
while(true)
{
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamWriter = new StreamWriter(networkStream);
StreamReader streamReader = new StreamReader(networkStream);
string line = streamReader.ReadLine();
Console.WriteLine("Read:" +line);
line=line.ToUpper()+ "!";
streamWriter.WriteLine(line);
streamWriter.Flush() ;
}
}
socketForClient.Close();
Console.WriteLine("Exiting...");
}
catch(Exception e)
{
Console.WriteLine(e.ToString()) ;
}
}
}
//Client Code
using System;
using System.Net.Sockets;
using System.Windows.Forms;
using System.IO ;
using System.ComponentModel ;
using System.Drawing;
public class Echoclient: Form
{
private Button b1;
private TextBox t1,ta;
TcpClient myclient;
private NetworkStream networkStream ;
private StreamReader streamReader ;
private StreamWriter streamWriter ;
public Echoclient()
{
InitializeComponent();
}
public static void Main()
{
Echoclient df=new Echoclient();
df.FormBorderStyle=FormBorderStyle.Fixed3D;
Application.Run(df);
}
public void InitializeComponent()
{
this.Closing+= new CancelEventHandler(form1_closing) ;
//connect to the "localhost" at the give port
//if you have some other server name then you can use that instead of "localhost"
try
{
myclient = new TcpClient("localhost", 1234);
}
catch
{
Console.WriteLine("Failed to connect to server at {0}:999", "localhost");
return;
}
//get a Network stream from the server
networkStream = myclient.GetStream();
streamReader = new StreamReader(networkStream);
streamWriter = new StreamWriter(networkStream);
}
//User can enter a text in the textbox and on click of the button the message will be sent to the server..
//then the Client waits and receives the response from the server which is displayed in the textarea..
private void b1_Click(object sender, EventArgs e)
{
ta.Text="" ;
if(t1.Text=="")
{
MessageBox.Show("Please enter something in the textbox");
t1.Focus();
return ;
}
try
{
string s;
streamWriter.WriteLine(t1.Text);
Console.WriteLine("Sending Message");
streamWriter.Flush();
s= streamReader.ReadLine();
Console.WriteLine("Reading Message") ;
Console.WriteLine(s) ;
ta.Text=s;
}
catch(Exception ee)
{
Console.WriteLine("Exception reading from Server:"+ee .ToString());
}
}
}
No comments:
Post a Comment