How to stop the while(true) in socket in Java - java

I am using Java Socket programming. When I click button the first time, the Socket is working perfectly. But button and other functions are not working anymore. All are disabled or do not react when I click them.
This is Main Class
JButton btnRemote = new JButton("Remote ");
btnRemote.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ServerInitiator ser=new ServerInitiator();
ser.initialize(4444);
}
});
Socket Class
public static void main(String args[]){
String port = JOptionPane.showInputDialog("Please enter listening port");
new ServerInitiator().initialize(5555);
}
public void initialize(int port){
try {
ServerSocket sc = new ServerSocket(port);
//Show Server GUI
drawGUI();
// drawGUI();
//Listen to server port and accept clients connections
while(true){
Socket client = sc.accept();
System.out.println("New client Connected to the server");
//Per each client create a ClientHandler
new ClientHandler(client,desktop);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

You should separate your GUI from your server logic. Anyway,
you can make the ClientHandler a Runnable, then spawn a new Thread for each new client:
// server is listening
while (true){
...
new Thread(new ClientHandler(client, desktop)).start();
...
}

Related

Java Multiple threads using a client socket

I'm creating a server based chat program that has multiple worker threads each handling a client on a socket. It has a single server socket that passes off the client to the worker thread.
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4001);
System.out.println("Listening server");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Connected");
Random rand= new Random();
int port=4001+rand.nextInt(5);
Worker worker = new Worker(port);
executor.execute(worker);
System.out.println("Thread started");
new PrintWriter(socket.getOutputStream(), true).println(port);
socket.close();
System.out.println("Closed");
// break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Worker implements Runnable {
private int port;
public Worker(int i) {
port=i;
}
#Override
public void run() {
worker();
}
private static Socket socket;
private static PrintWriter out;
private static BufferedReader in;
private void worker() {
try {
ServerSocket serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("Received: " + line);
switch (line) {
case ("Button Press"):
System.out.println("Handled button");
out.println("Button acknowledged");
break;
case ("Give me some data"):
System.out.println("Handled data");
out.println("Have some data");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This works fine, however the issue is when I have an automated request by the client to check for messages and the user provides some input at the same type. This causes conflict as the actual methods take a couple of seconds to run and if more input is received then the request won't be handled because its in the middle of the method. For example:
private static BufferedReader in;
private static PrintWriter out;
public static void main(String[] args) {
Main main=new Main();
main.createWindow();
try {
Socket init = new Socket(InetAddress.getLocalHost(), 4001);
int port
=Integer.parseInt
(new BufferedReader
(new InputStreamReader(init.getInputStream())).readLine());
init.close();
Socket socket=new Socket(InetAddress.getLocalHost(), port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
try {
Thread.sleep(5000);
out.println("Give me some data");
if(in.readLine().equals("Have some data")){
System.out.println("Data recieved");
}else{
System.out.println("Data not recieved");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void createWindow(){
JFrame frame =new JFrame("This is a button");
Container pane=getContentPane();
JButton button=new JButton("This is a button");
button.addActionListener(this);
pane.add(button);
frame.setTitle("Messaging");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
frame.setVisible(true);
frame.setSize(400, 350);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button press");
try {
out.println("Button Press");
if(in.readLine().equals("Button acknowledged")){
System.out.println("Button complete");
}else{
System.out.println("Button fail");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
If the button is pressed whilst the server is fetching data it conflicts and the wrong response is sent. So how would I deal with this? If I create a separate socket to just handle automated checks that's double the amount of threads the server has to cope with. Is there a better solution?
And please can you try to explain as this is a new area for me.
Your problem is that you have two threads interacting with the socket, your main thread and the Swing event handling thread. This means that the two threads can queue two different things, and the responses may be picked up by the wrong thread. The simplest way to get where you want to be is to put all the socket interaction in one thread.
There are two ways to do this. One would be for the main thread to queue the periodic automated checks to the Swing event handling thread. However, that's a bit complicated and also possibly buggy as the actual Swing threading model is different from what's documented.
The other way to do it would be for the Swing event handling thread to queue button presses to the main thread. In this case, you would queue the button press to the main thread using proper synchronization. The main loop of the main thread would check for button presses and send them through the socket and wait for the proper response.

Server is not able to receive the text from client java

I am creating an app in which client can send some text to server on button click.I want to print that text on console server side,but whenever client side button is pressed nothing happens.
and after sometimes i got this line on console android.support.v7.widget.AppCompatEditText#b2253390.
I am not getting why this is happening ?
SERVER CODE :
public static ServerSocket server = null;
public static Socket client = null;
public static void main(String []arg)throws IOException{
try {
server = new ServerSocket(8002);
System.out.println("Server Started...............");
while(true){
client = server.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
String msg = in.readLine();
System.out.println("and: "+msg);
}
}catch(IOException r){
System.out.println("error :"+r.getMessage());
}
}
CLIENT CODE:
public void send(){
send.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Socket cs = null;
try {
cs = new Socket("192.168.1.100", 8002);
DataOutputStream out = new DataOutputStream(cs.getOutputStream());
out.writeBytes(text.toString());
} catch (IOException e) {
Toast.makeText(KeyboardActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
);
}
It is because text is an EditText.
I think you actually meant,
out.writeBytes(text.getText().toString());
Instead of,
out.writeBytes(text.toString());

Java chat room UI blank and unresponsive

I have followed the newboston tutorials and made a chatroom with server side code and client side code. I wanted to build them together in one app.
My issue is that the client is blank, I used the standalone server from the tutorial.
picture of server chat working with the client chat being a blank window
But if I close the server first, all of the chat appears on the client chat, as in it is all instantly updated.
client chat updated, all previous chats messages displayed.
Standalone server:
package instantmessage;
import javax.swing.JFrame;
public class ServerChatroom {
public static void main(String[] args) {
Server runServer = new Server();
runServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
runServer.startServer();
}
}
package instantmessage;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame{
private JTextField userText; //where you type in message
private JTextArea chatWindow; //displays the conversation
private ObjectOutputStream output; //information sent to the recipent
private ObjectInputStream input; //information being received from the recipent
private ServerSocket server;
private Socket connection; //the connection between you and the recipent's computer
//setting up GUI.
public Server(){
super("Instant Messanger - Server"); //the piece in the brackets is the title off the app.
userText = new JTextField();
userText.setEditable(false);//without having a connection you can't send messages.
userText.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand()); //sends string that was typed into text field.
userText.setText(""); //after text has been sent, remove the previous message sent.
}
}
);
add(userText, BorderLayout.NORTH); //add userText to GUI, make chat window top of the screen.
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow)); //scrolling pane created for all the chats.
setSize(450,200);
setVisible(true);
}
//create the server and run the serve.
public void startServer(){
try{
server = new ServerSocket(6789, 100); //Server socket. first one the server socket, the second how many clients can wait for connection.
while(true){//the loop should run forever. The main program.
try{//connect and allow conversation with another
waitForConnection();//wait for someone to connect with server.
setupStream(); //create the connection between another computer.
whileChatting(); //allow messages to be sent back and forth during chat.
}catch(EOFException eofException){ //whenever the conversation is ended.
showMessage("\n Server overloaded, connection terminated by the server.");
}finally{
closeServer();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, after connection established display connection details.
private void waitForConnection() throws IOException{
showMessage("Waiting for connection to be established...\n"); //so user has something to see, knows program isn't frozen.
connection = server.accept(); //accept the connection.
showMessage("Connection established with " + connection.getInetAddress().getHostName());
}
//gets stream for send/receiving of data.
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //create pathway for connection to other computer.
output.flush(); //good practice. Cleans up data that was "left over"
input = new ObjectInputStream(connection.getInputStream()); //creates pathway to receive data from other PC.
//no flush for input, the other side has to flash.
showMessage("Connection now active");
}
//sending text back and forth
//this receives the data from the connected computer and displays it.
private void whileChatting() throws IOException{
String message = " You are now connected ";
sendMessage(message);
ableToType(true);
do{//have conversation while client doesn't send CLIENT - END.
try{
message = (String) input.readObject(); //read whatever message is incoming.
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n user has sent garbage.");
}
}while(!message.equals("CLIENT - END"));
}
//close streams/sockets after chat ends. "Good housekeeping". Frees up memory.
private void closeServer(){
showMessage("\n\tTerminating connection...");
ableToType(false);
try{
input.close(); //terminate stream from
output.close(); //terminate stream to
connection.close(); //terminate connection
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to connected computer.
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message); //creates an object of message and sends it along the output stream.
output.flush(); //remove once it's finished sending.
showMessage("\nSERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n error sending message"); //print out the error in the chat window that the message was not sent.
}
}
//shows messages on main chat area. Updates the chatWindow so it is always current.
private void showMessage(final String string){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
chatWindow.append(string);
}
}
);
}
//sets the textfield editable so that the user can type in it
private void ableToType(final boolean bool){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
userText.setEditable(bool);
}
}
);
}
}
My code for the standalone piece:
package chatroomomni;
import javax.swing.JFrame;
public class ChatRoomOmni {
public static void main(String[] args) {
MainMenu runProgram = new MainMenu();
runProgram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package chatroomomni;
//the user has to chose to be a client or a server.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
//layout: first button is host server, second line is a JTextLabel telling user to enter server IP, JTextField next to it for server IP, connect button next.
public class MainMenu extends JFrame{
private JButton hostServer = new JButton("Host server");
private JLabel labelEnterServerIP = new JLabel("Enter Server IP: ");
private JTextField serverIPInput = new JTextField(25);
private JButton connectServer = new JButton("Connect to server");
//constructor
public MainMenu(){
super("Instant Messenger - Main Menu");
serverIPInput.setEditable(true);
//action listener for the host server.
hostServer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
Server runServer = new Server();
runServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CloseFrame();
runServer.startServer();
}
});
//action listener for connect to server.
connectServer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(!String.valueOf(serverIPInput.getText()).equals("")){
System.out.println(String.valueOf(serverIPInput.getText()));
Client client = new Client(String.valueOf(serverIPInput.getText()));
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CloseFrame();
client.startClient();
}
}
});
setLayout(new FlowLayout());
//add items to frame.
add(hostServer);
add(labelEnterServerIP);
add(serverIPInput);
add(connectServer);
setSize(1000, 500);
setVisible(true);
}
public void CloseFrame(){
super.dispose();
}
}
package chatroomomni;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame{
private JTextField userText; //where you type in message
private JTextArea chatWindow; //displays the conversation
private ObjectOutputStream output; //information sent to the recipent
private ObjectInputStream input; //information being received from the recipent
private Socket connection; //the connection between you and the recipent's computer
private String message;
private String serverIP;
public Client(String host){
super("Instant Messenger - Client");
serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(500, 400);
setVisible(true);
}
//connect to the server,
public void startClient(){
try{
connectToServer();
setupStream();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeClient();
}
}
private void connectToServer() throws IOException{
showMessage("Attempting to connect to server...\n");
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage("Connection established to: " + connection.getInetAddress().getHostAddress());
}
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //create pathway for connection to other computer.
output.flush(); //good practice. Cleans up data that was "left over"
input = new ObjectInputStream(connection.getInputStream()); //creates pathway to receive data from other PC.
//no flush for input, the other side has to flash.
showMessage("Connection now active");
}
private void whileChatting() throws IOException{
String message = " You are now connected ";
sendMessage(message);
ableToType(true);
do{//have conversation while server doesn't send SERVER - END.
try{
message = (String) input.readObject(); //read whatever message is incoming.
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n server has sent garbage.");
}
}while(!message.equals("SERVER - END") || !message.equals("SERVER - TERMINATE CONNECTION"));
}
private void closeClient(){
showMessage("\n\tTerminating connection...");
ableToType(false);
try{
input.close(); //terminate stream from
output.close(); //terminate stream to
connection.close(); //terminate connection
}catch(IOException ioException){
ioException.printStackTrace();
}
}
private void sendMessage(final String message){
try{
output.writeObject("CLIENT - " + message); //creates an object of message and sends it along the output stream.
output.flush(); //remove once it's finished sending.
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n error sending message"); //print out the error in the chat window that the message was not sent.
}
}
private void showMessage(final String string){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
chatWindow.append(string);
}
}
);
}
private void ableToType(final boolean bool){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
userText.setEditable(bool);
}
}
);
}
}
package chatroomomni;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame{
private JTextField userText; //where you type in message
private JTextArea chatWindow; //displays the conversation
private ObjectOutputStream output; //information sent to the recipent
private ObjectInputStream input; //information being received from the recipent
private ServerSocket server;
private Socket connection; //the connection between you and the recipent's computer
//setting up GUI.
public Server(){
super("Instant Messanger - Server"); //the piece in the brackets is the title off the app.
userText = new JTextField();
userText.setEditable(false);//without having a connection you can't send messages.
userText.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand()); //sends string that was typed into text field.
userText.setText(""); //after text has been sent, remove the previous message sent.
}
}
);
add(userText, BorderLayout.NORTH); //add userText to GUI, make chat window top of the screen.
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow)); //scrolling pane created for all the chats.
setSize(450,200);
setVisible(true);
}
//create the server and run the serve.
public void startServer(){
try{
server = new ServerSocket(6789, 100); //Server socket. first one the server socket, the second how many clients can wait for connection.
while(true){//the loop should run forever. The main program.
try{//connect and allow conversation with another
waitForConnection();//wait for someone to connect with server.
setupStream(); //create the connection between another computer.
whileChatting(); //allow messages to be sent back and forth during chat.
}catch(EOFException eofException){ //whenever the conversation is ended.
showMessage("\n Server overloaded, connection terminated by the server.");
}finally{
closeServer();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, after connection established display connection details.
private void waitForConnection() throws IOException{
showMessage("Waiting for connection to be established...\n"); //so user has something to see, knows program isn't frozen.
connection = server.accept(); //accept the connection.
showMessage("Connection established with " + connection.getInetAddress().getHostName());
}
//gets stream for send/receiving of data.
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //create pathway for connection to other computer.
output.flush(); //good practice. Cleans up data that was "left over"
input = new ObjectInputStream(connection.getInputStream()); //creates pathway to receive data from other PC.
//no flush for input, the other side has to flash.
showMessage("Connection now active");
}
//sending text back and forth
//this receives the data from the connected computer and displays it.
private void whileChatting() throws IOException{
String message = " You are now connected ";
sendMessage(message);
ableToType(true);
do{//have conversation while client doesn't send CLIENT - END.
try{
message = (String) input.readObject(); //read whatever message is incoming.
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n user has sent garbage.");
}
}while(!message.equals("CLIENT - END"));
}
//close streams/sockets after chat ends. "Good housekeeping". Frees up memory.
private void closeServer(){
showMessage("\n\tTerminating connection...");
ableToType(false);
try{
input.close(); //terminate stream from
output.close(); //terminate stream to
connection.close(); //terminate connection
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to connected computer.
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message); //creates an object of message and sends it along the output stream.
output.flush(); //remove once it's finished sending.
showMessage("\nSERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n error sending message"); //print out the error in the chat window that the message was not sent.
}
}
//shows messages on main chat area. Updates the chatWindow so it is always current.
private void showMessage(final String string){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
chatWindow.append(string);
}
}
);
}
//sets the textfield editable so that the user can type in it
private void ableToType(final boolean bool){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
userText.setEditable(bool);
}
}
);
}
}
All the netbeans project files uploaded to zippyshare: www116(dot)zippyshare(dot)com/v/qAa5BGWn/file(dot)html (not allowed to post more than 2 links, I apologize for trying to circumvent the rule but it is relevant)
Any help would be appreciated.

How to build a multithreading socket server

I try to build server that could talk with several clients at the same time.
But there are some problems with the thread, and the code doesn't work well.
Could you tell me what is wrong with the thread part? Thank you very much.
public class ServerMulti extends JFrame implements ActionListener{
private static final int PORT = 60534;
private JTextField textField = new JTextField();
private static JTextArea textArea = new JTextArea();
private JButton button = new JButton();
public static ServerSocket server;
public static Socket socket;
public static BufferedReader in;
public static PrintWriter out;
public ServerMulti(){
/*
* build up GUI
*/
setTitle("Server Multi");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,400);
setBackground(Color.white);
setLayout(new BorderLayout());
button.setText("Send");
button.setSize(300, 50);
textField.setText("Type here");
textArea.setSize(300, 50);
add(textField, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setLocation(300, 100);
button.addActionListener(this);
setVisible(true);
}
/*
* print out the information that need to sent to clients
*
*/
public void actionPerformed(ActionEvent e) {
textArea.append(textField.getText()+"\n");
out.println(textField.getText());
textField.setText("");
}
public static void main(String[] args) throws IOException{
new ServerMulti();
//build up the socket and server
try{
server = new ServerSocket(PORT);
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
textArea.append("Connected. "+" Port: " + PORT + "\n");
while(true){
worker w = new worker();
Thread t = new Thread(w);
t.start();
}
}catch (IOException e) {
System.out.println("Accept failed:" +PORT);
System.exit(-1);
}
}
//to the same server, different sockets are created connecting to different client
public static class worker implements Runnable{
public void run() {
String msg;
/*
* the "in.readLine()" give the data only once
* 1. so we save the information to a String from the socket
* 2. Then sent out a feedback to client, through socket
* 3. print out the String we just collected
*/
while(true){
try {
msg = in.readLine();
out.println("Server received : " + msg);
textArea.append(msg+"\n");
} catch (IOException e) {
System.out.println("Fail");
e.printStackTrace();
}
}
}
}
}
There are a couple of problems with this, but in terms of multithreading the server: ServerSocket.accept() blocks until a new client attempts to connect. In your code this only happens once; so only one client will be accepted. The layout should instead be something like this:
ServerSocket ss = new ServerSocket(PORT);
while (LISTENING) {
Socket sock = ss.accept();
Handler handler = new Handler(sock);
new Thread(handler).start();
//With the LISTENING variable dealt with as well
}
Here the class Handler should be a Runnable class that deals with the socket on another thread. The while loop can then go back and accept a new connection.

Connecting to server with multiple clients

i'm trying to create a server that allows several clients, I can connect with one client fine, but I cant with two. The was I try to connect two clients to the server is by creating two client objects and one server in a main method. Here is the code for the Server:
public class DraughtsSever extends JFrame{
JPanel panel;
JTextArea gamesList;
ServerSocket draughtsSS;
JScrollPane scroll;
Socket s;
int i = 0;
DraughtsSever(){
panel = new JPanel();
panel.setPreferredSize(new Dimension(350,350));
gamesList = new JTextArea();
//scroll.setPreferredSize(new Dimension(350,350));
gamesList.setPreferredSize(new Dimension(300,300));
//scroll.add(GamesList);
//scroll = new JScrollPane(GamesList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//panel.add(scroll);
this.add(panel);
panel.add(gamesList);
this.setSize(400,400);
this.setVisible(true);
this.setTitle("Draughts Server");
panel.add(gamesList);
allowConnections();
}
public void allowConnections(){
gamesList.append("Server listening on port 50000...");
try{
while(true){
draughtsSS = new ServerSocket(50000);
//s = draughtsSS.accept();
new Thread(new TestT(draughtsSS.accept())).start();
//t.start();
}
}
catch(IOException e){
System.out.println("Error :"+e.getMessage());
}
}
class TestT implements Runnable{
Socket s;
TestT(Socket s){
this.s = s;
}
public void run(){
try{
PrintWriter out = new PrintWriter(s.getOutputStream());
Scanner in = new Scanner(s.getInputStream());
gamesList.append("\n"+s.getInetAddress().toString() +" has connected.");
JOptionPane.showMessageDialog(new JFrame(), "Successfully connected");
out.println("hello");
System.out.println(s.getInetAddress().toString() +" has connected.");
}
catch(IOException e){
}
}
}
}
Here is the method in the client that I use to connect to the server
private void setupConnection(String serverIP, String port){
int portInt = Integer.parseInt(port);
try{
InetAddress IP = InetAddress.getByName(serverIP);
int intPort = Integer.parseInt(port);
Socket clientSocket = new Socket(IP,intPort);
JOptionPane.showMessageDialog(new JFrame(), "Successfully connected to Server");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
Scanner in = new Scanner(clientSocket.getInputStream());
//in.
}
catch(Exception e){
System.out.println("ErrorC :" +e.getMessage());
}
}
}
}
I think you should only create the server socket once, so move this outside of the while loop:
draughtsSS = new ServerSocket(50000);
You don't need to keep re-creating this because when clients connect they automatically get moved to a different socket when you call
draughtsSS.accept()

Categories