简体   繁体   中英

Sockets and Java chat

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:

  • Start a new thread for each new client TCP connection as previous responders suggest. This is OK for smallish/toy servers, and when you are just starting playing with sockets. The big downside here is that this approach does not scale - just think about having a thousand concurrent clients ...
  • Use IO multiplexing with non-blocking sockets as provided by Java NIO package , dispatching accept/read/write events to registered callbacks. You can extend this with work-item queue(s) and a pool of pre-allocated worker threads to take advantage of multiple cores/CPUs in your hardware.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM