Hello all i havent played with java in a couple months and was recently inteested in writing a socket for java. socket read/write operations confused me for a bit, I managed to make a quik fix and get it working but then i decided to take it a step further and add a thread to handle reading data from the socket to allow read/write operations efficently.
My socket works and all now, im attaching the source to the simple socket i created, if anyone is experienced in java i would appreciate your feedback. Did i attack this read/write problem in the proper way? I have only began to scratch the surface of creating seperate threads and i understand the importance of it, just wondering if my solution by adding a thread to the socket for reading data was the right way to attack this problem.
Any insight is appreciated
Thanks..
Code:
/**
*
* @author mojo
*/
public class Demo
{
public static void main(String[] args)
{
J_Socket sock = new J_Socket(java.net.Proxy.NO_PROXY, "yahoo.com", 80);
sock.write_Socket_Data("GET ");
}
}
class J_Socket extends Socket{
private PrintWriter out = null;
private BufferedReader in = null;
private String response = null;
private void showMessage(Object msg)
{
javax.swing.JOptionPane.showMessageDialog(
null,String.valueOf(msg));
}
public J_Socket(Proxy proxy, String remoteHost, int remotePort) {
super(proxy);
InetSocketAddress remoteAddress = new
InetSocketAddress(remoteHost, remotePort);
try
{
this.connect(remoteAddress);
if(this.isConnected())
{
out = new PrintWriter(this.getOutputStream(), true);
in = new BufferedReader( new
InputStreamReader(this.getInputStream()));
new J_sckReader("socketReader").start();
}
}
catch(Exception e)
{System.out.println(e.toString());}
}
public void write_Socket_Data(String Packet)
{
out.println(Packet);
}
private class J_sckReader extends Thread {
public J_sckReader(String str) {
super(str);
}
@Override
public void run()
{
try
{
while ((response = in.readLine()) != null)
{
System.out.println("Server: " + response);
}
} catch (Exception e)
{ showMessage(e.toString());}
}
}
}