I'm new to java and i'm trying to learn how to use sockets.
I'm trying to write a simple text messenger, server - client, but i don't know how to make the server always listening for client's stream:
Here's the server code, by now it just manages 1 incoming connection, when the client connects, the server send a message to it:
import java.net.*;
import java.io.*;
public class SocketServer {
private InetAddress ServerAddress;
private int ServerPort;
private int ServerQueue;
private ServerSocket Server;
public SocketServer(String ServerAddress, int ServerPort, int ServerQueue)
{
try
{
this.ServerAddress = InetAddress.getByName(ServerAddress);
}
catch (UnknownHostException uhe)
{
uhe.printStackTrace();
}
this.ServerPort = ServerPort;
}
public boolean ServerCreate()
{
try
{
Server = new ServerSocket(this.ServerPort, 10, this.ServerAddress);
System.out.println("System Message: Server started!");
return true;
}
catch(IOException ioe)
{
ioe.printStackTrace();
System.out.println("System Message: Can't start server!");
return false;
}
}
public void ServerStartListening()
{
int exit = -1;
while(exit < 1)
{
try
{
Socket client = this.Server.accept();
OutputStream clientout = client.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientout));
bw.write("Welcome: "+client.toString());
bw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
Sorry for my bad english.
You need to implement multi-threading in order to listen for multiple incoming requests. Refer this link : a very nice multi-threaded server example by oracle
You need to read sth. about threads. Here is an initial code:
ServerSocket socketListener;
DoSthWithThisSocket doSthWithThisSocketObj;
socketListener = new ServerSocket(LISTENINGPORT);
Socket socket;
Thread doSthWithThisSocketThread;
while (continueSocketListening()) {
socket = socketListener.accept();
doSthWithThisSocketObj = new DoSthWithThisSocket(socket);
doSthWithThisSocketThread = new Thread(doSthWithThisSocketObj);
doSthWithThisSocketThread.start();
}
There are two main options for doing multi-client socket servers in Java:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.