basic sockets
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   mike_jarito
Posted On:   Tuesday, June 4, 2002 04:05 AM

can somebody please enlighten me on how to develop socket applications, what io classes to use, when to use them. Also im confused why the code below does not work (they just hangs until timeout)...do i have to really hard code something like checking for a "bye" keyword for the while loop below to exit? ON THE SERVER: try{ in = new BufferedReader(new InputStreamReader(this.sock.getInputStream())); out=new PrintWriter(this.sock.getOutputStream(),true); //read request String temp; StringBuffer bufResponse=new StringBuffer(); while((temp=in.readLine())!=null){ bufResponse.append(temp); //do i really need to place a   More>>

can somebody please enlighten me on how to develop socket applications, what io classes to use, when to use them. Also im confused why the code below does not work (they just hangs until timeout)...do i have to really hard code something like checking for a "bye" keyword for the while loop below to exit?

ON THE SERVER:



try{

in = new BufferedReader(new InputStreamReader(this.sock.getInputStream()));

out=new PrintWriter(this.sock.getOutputStream(),true);


//read request

String temp;

StringBuffer bufResponse=new StringBuffer();

while((temp=in.readLine())!=null){

bufResponse.append(temp);

//do i really need to place a check here?

//if(temp.equals("bye") break;

}


System.out.println("Received: "+bufResponse.toString());

out.println(bufResponse.toString());

//cleanup

in.close();

out.close();

sock.close();

}

catch(IOException e){

e.printStackTrace();

}




ON THE CLIENT:


try{

sock=new Socket(host,port);

sock.setSoTimeout(10000); <


PrintWriter out=new PrintWriter(sock.getOutputStream(),true);


BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()));


//send request

System.out.print("SENT: ");

out.print("Hello");

out.println("Hello2");

out.flush();



//receive response

String temp;

StringBuffer bufResponse=new StringBuffer();

while((temp=in.readLine())!=null){

bufResponse.append(temp);

}

System.out.println("RECEIVED: "+bufResponse.toString());


out.close();

//cleanup

in.close();

//out.close();

sock.close();

}

catch(UnknownHostException f){

f.printStackTrace();

}

catch(IOException e){

e.printStackTrace();

}

}

   <<Less

Re: basic sockets

Posted By:   Philip_Scuderi  
Posted On:   Thursday, June 27, 2002 01:29 PM

Here's a very simple Client Applet - Server Application that I wrote. The client opens a socket connection to the server when you run the applet. Then when you type into the textfield the message is sent to the server. The server then echos the message right back and it is then displayed on the client applet. Here is the code.



import java.io.*;


import java.net.*;



public class Server

{

public static void main(String[] args)

{

new Server().start();

}



public void start()

{

try

{

ServerSocket serverSocket = new ServerSocket(8080, 100);

while (true) new ConnectionThread(this, serverSocket.accept()).start();

}



catch (Exception exception)

{

exception.printStackTrace();

System.exit(1);

}

}



public void processInput(ConnectionThread connectionThread, Object object)

{

try { System.out.println((String)object); } catch (Exception exception) { }

connectionThread.sendData(object);

}



class ConnectionThread extends Thread

{



private Server parent;

private Socket clientSocket;

private ObjectOutputStream output;

private ObjectInputStream input;



public ConnectionThread(Server parent, Socket clientSocket) throws IOException

{

this.parent = parent;

this.clientSocket = clientSocket;

this.clientSocket.setKeepAlive(true);

this.setDaemon(true);

}



public void run()

{

try

{

output = new ObjectOutputStream(clientSocket.getOutputStream());

output.flush();

input = new ObjectInputStream(clientSocket.getInputStream());

do

{

try

{

parent.processInput(this, input.readObject());

}

catch (Exception exception)

{

break;

}

} while (true);

try

{

output.close();

}

catch (Exception exception)

{ }

try

{

input.close();

}

catch (Exception exception) { }

try

{

clientSocket.close();

}

catch (Exception exception) { }

}

catch (Exception exception)

{

exception.printStackTrace();

}

parent = null;

}



public void sendData(Object object)

{

try

{

output.writeObject(object);

}

catch (IOException ioException)

{ }

}

}

}



import java.io.*;

import java.net.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

import javax.swing.text.*;



public class Client extends JApplet implements Runnable

{

private DefaultStyledDocument doc = new DefaultStyledDocument();

private JTextPane displayArea = new JTextPane(doc);

private JTextField enterField = new JTextField();

private SimpleAttributeSet defaultStyle = new SimpleAttributeSet();

private ObjectOutputStream output;

private ObjectInputStream input;

private boolean error;

private Socket client;

private Thread runner;



public void init()

{

Container container = this.getContentPane();

container.add(new JScrollPane(displayArea), BorderLayout.CENTER);

container.add(enterField, BorderLayout.SOUTH);

enterField.setEnabled(false);

enterField.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent event)

{

enterField.setText("");

sendData(event.getActionCommand());

}

});

}



public void start()

{

if (runner == null)

{

runner = new Thread(this);

runner.start();

}

}



public void stop()

{

if (runner != null)

runner = null;

}



public void run()

{

do

{

try

{

connectToServer();

getStreams();

enterField.setEnabled(true);

enterField.grabFocus();

processConnection();

enterField.setEnabled(false);

closeConnection();

}

catch (Exception exception)

{ }

} while (!error);

}



private void getStreams() throws IOException

{

output = new ObjectOutputStream(client.getOutputStream());

output.flush();

input = new ObjectInputStream(client.getInputStream());

}



private void connectToServer() throws IOException

{

try

{

client = new Socket(InetAddress.getByName(getCodeBase().getHost()), 8080);

client.setKeepAlive(true);

display("Connected to: " + client.getInetAddress().getHostName());

}

catch (UnknownHostException unknownHostException)

{

display("Error: Unknown Host");

error = true;

}

catch (ConnectException connectException)

{

display("Error: Connection Refused
To try again reload this applet.");

error = true;

}

}



private void processConnection() throws IOException

{

do

{

try

{

display((String)input.readObject());

}

catch (SocketException socketException)

{

break;

}

catch (EOFException eofException)

{

break;

}

catch (Exception exception)

{

display(exception.toString());

break;

}



} while (true);

}



private void closeConnection()

{

try { output.close(); } catch (Exception exception) { }

try { input.close(); } catch (Exception exception) { }

try { client.close(); } catch (Exception exception) { }

}



private synchronized void sendData(Object object)

{

try

{

output.writeObject(object);

output.flush();

}

catch (IOException ioException)

{

display("Error writing object.");

}

}



public synchronized void display(String str)

{

try

{

if (doc.getLength() != 0)

doc.insertString(doc.getLength(), "
", defaultStyle);

doc.insertString (doc.getLength(), str, defaultStyle);

displayArea.setCaretPosition(doc.getLength());

}

catch (BadLocationException ble)

{ }

}



}
About | Sitemap | Contact