1.i am new to java so im a noob but im trying to make this chat server and client the server so far will run but the client wont and returns the error in the title please help and try and keep it noob friendly :)
import java.net.*;
import java.io.*;
import java.awt.*;
@SuppressWarnings("serial")
class chatClient extends Frame implements Runnable
{
Socket soc;
TextField tf;
TextArea ta;
Button btnSend,btnClose;
String sendTo;
String LoginName;
Thread t=null;
DataOutputStream dout;
DataInputStream din;
chatClient(String LoginName,String chatwith) throws Exception
{
super(LoginName);
this.LoginName=LoginName;
sendTo=chatwith;
tf=new TextField(50);
ta=new TextArea(50,50);
btnSend=new Button("Send");
btnClose=new Button("Close");
soc=new Socket("127.0.0.1",5211);
din=new DataInputStream(soc.getInputStream());
dout=new DataOutputStream(soc.getOutputStream());
dout.writeUTF(LoginName);
t=new Thread(this);
t.start();
}
@SuppressWarnings("deprecation")
void setup()
{
setSize(600,400);
setLayout(new GridLayout(2,1));
add(ta);
Panel p=new Panel();
p.add(tf);
p.add(btnSend);
p.add(btnClose);
add(p);
show();
}
@SuppressWarnings("deprecation")
public boolean action(Event e,Object o)
{
if(e.arg.equals("Send"))
{
try
{
dout.writeUTF(sendTo + " " + "DATA" + " " + tf.getText().toString());
ta.append("\n" + LoginName + " Says:" + tf.getText().toString());
tf.setText("");
}
catch(Exception ex)
{
}
}
else if(e.arg.equals("Close"))
{
try
{
dout.writeUTF(LoginName + " LOGOUT");
System.exit(1);
}
catch(Exception ex)
{
}
}
return super.action(e,o);
}
public static void main(String[] args) throws Exception
{
chatClient Client=new chatClient(args[0], args[1]);
Client.setup();
}
public void run()
{
while(true)
{
try
{
ta.append( "\n" + sendTo + " Says :" + din.readUTF());
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
I suspect you're starting it with:
java chatClient
You need to specify the login name and who you want to chat with, e.g.
java chatClient fred george
Otherwise args
will be an empty array, so evaluating args[0]
or args[1]
in main
will fail.
I'd also strongly advise you to fix both your indentation and your naming - follow the standard Java naming conventions.
See more on this question at Stackoverflow