Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Servers, Clients, sockets

Status
Not open for further replies.

fatcodeguy

Programmer
Feb 25, 2002
281
CA
I have a serversocket which implements a socket to recieve objects from a client server. I'm wondering if more than one person can connect to one socket port, (because getInetAddress only returns 1 inet address) and if a connection is maintained once it's been connected to. here's my code (which I got online)

/* This class represents the server*/

//import necessary packages
import java.net.*;
import java.io.*;
import java.util.*;

public class Server {
private ServerSocket serverSocket = null;
private int serverPort = 5700;

//main function
public static void main(String[] args) throws IOException {
System.out.println("Initiating Server...");
Server s = new Server();
try { s.initServer();}
catch (Exception e) { System.out.println(e.toString());}
}

// Initializes the server.
public void initServer() throws IOException {
//open port
try {serverSocket = new ServerSocket(serverPort);}
catch (IOException e) {
System.out.println("ERROR: Another application is listening to port "+serverPort+ ".\n"+e);
System.exit(0);
}

// infinite loop
boolean listening = true;
while (listening) {
Socket s = serverSocket.accept();
ServerThread st = new ServerThread(s, this);
st.start();
}
serverSocket.close();
}
}

class ServerThread extends Thread {
private Socket socket = null;
private Server server;

//constructor
public ServerThread(Socket socket, Server server) {
super("ServerThread");
this.socket = socket;
this.server = server;
}

//get objects from client
public void run() {
Object objectFromClient = null;
try {
ObjectInputStream objIn = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
objectFromClient = objIn.readObject();

if (objectFromClient.getClass().equals(String.class)) {
System.out.println(">> String object recieved>>"+objectFromClient.toString());
reply("String object recieved by server");
}
join();
}
catch (StreamCorruptedException sce) {
System.err.println(sce.toString());
}
catch (Exception e) {
e.printStackTrace();
}
}


//takes the recieved object and sends it to the client.
private void reply(Object obj) {
try {
ObjectOutputStream objOut = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
objOut.writeObject(obj);
objOut.flush();
objOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Also, is there a way to shut down whatever is listening to a specific socket port? Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top