Skip to content

Instantly share code, notes, and snippets.

@vnkdj5
Created July 4, 2017 06:30
Show Gist options
  • Save vnkdj5/8371fe1c99cb052d2082154833300de9 to your computer and use it in GitHub Desktop.
Save vnkdj5/8371fe1c99cb052d2082154833300de9 to your computer and use it in GitHub Desktop.
Client Chat With Threading
import java.net.*;
import java.io.*;
public class Client implements Runnable {
public boolean b=true;
Socket s;
DataInputStream din ;
DataOutputStream dout;
BufferedReader br;
String str,str2;
Thread t1,t2;
public Client() throws UnknownHostException, IOException
{
s=new Socket("localhost",8088);
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
str="";str2="";
t1=new Thread(this,"t1");
t2=new Thread(this,"t2");
t1.start();t2.start();
}
public static void main(String[] args) throws Exception {
new Client();
}
public void run(){
if(Thread.currentThread().getName().equals("t1"))
{
while(b)
{try
{
str=din.readUTF();
}
catch(Exception e)
{
System.out.println("Error");
}
if(str.equals("end"))
{
b=false;
t1.stop();t2.stop();
}
System.out.println("Server:"+str);
}
}
else if(Thread.currentThread().getName().equals("t2"))
{
while(b)
{
try
{
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment