This question already has an answer here:
GUI freeze after click on button
(1 answer)
Closed 6 years ago.
im creating a client/server program. Clients need to connect to a server that is connected to a interface and every 5 min clients send a String that will be showed in the server's inteface.
This is the Server Interface code:
public class MainServer implements ActionListener {
public static JFrame f_principale;
JButton avvio_server;
JButton ferma_server;
public static JLabel risultato;
JButton richiesta;
Server server;
public static JTextArea ritorni;
public MainServer(){
UI_LOADER();
}
public void BUTTON_LOADER(){
avvio_server = new JButton("Avvia");
ferma_server = new JButton("Ferma");
richiesta = new JButton("Richiedi");
avvio_server.addActionListener(this);
ferma_server.addActionListener(this);
richiesta.addActionListener(this);
}
public void TEXT_LOADER(){
risultato = new JLabel();
risultato.setText("prova");
ritorni = new JTextArea();
}
public void WINDOW_LOADER(){
f_principale = new JFrame("Centro Meteorologica");
f_principale.setSize(800, 600);
f_principale.setVisible(true);
f_principale.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f_principale.setBackground(Color.gray);
f_principale.add(avvio_server);
f_principale.add(ferma_server);
f_principale.add(richiesta);
f_principale.add(ritorni);
f_principale.add(risultato);
avvio_server.setBounds(100, 400, 200, 100);
ferma_server.setBounds(500, 400, 200, 100);
richiesta.setBounds(350, 400, 100, 50);
ritorni.setBounds(100, 50, 600, 300);
risultato.setBounds(300, 530, 200, 50);
}
public void UI_LOADER(){
BUTTON_LOADER();
TEXT_LOADER();
WINDOW_LOADER();
}
public static void main(String[] args) {
MainServer m1 = new MainServer();
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
if(button.getText() == "Avvia"){
System.out.print("Server avviato");
Thread server = new Server();
System.out.print("Server avviato");
server.run();
System.out.print("Server avviato");
}
if(button.getText() == "Ferma"){
try {
server.closeServer();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(button.getText() == "Richiedi"){
}
}
And this is the Server code:
public class Server extends Thread{
private ServerSocket serverSocket;
int clientPort;
ArrayList clients = new ArrayList();
public void run(){
Socket client;
try {
MainServer.ritorni.setText("Server Aperto");
serverSocket= new ServerSocket(4500);
System.out.println("Server Aperto");
} catch (IOException e) {
MainServer.risultato.setText("Errore nel aprire il server");
}
while(true){
client = null;
try {
client=serverSocket.accept();
MainServer.risultato.setText("Dispositivo collegato");
} catch (IOException e) {
MainServer.risultato.setText("Errore nel collegare il dispositivo");
}
clients.add(client);
Thread t=new Thread(new AscoltoDispositivo(client));
t.start();
}
}
public void closeServer() throws IOException{
serverSocket.close();
}
public void broadcastMessage(BufferedReader is, DataOutputStream os, Socket client) throws IOException{
for(Iterator all=clients.iterator();all.hasNext();){
Socket cl=(Socket)all.next();
sendMessage(cl);
}
}
private void sendMessage(Socket cl) throws IOException{
new DataOutputStream(cl.getOutputStream()).writeBytes("ASKRESPONSE");
}
}
class AscoltoDispositivo implements Runnable{
DataOutputStream os;
BufferedReader is;
Socket client;
static String tempReceived = null;
public AscoltoDispositivo(Socket client){
this.client=client;
try{
is= new BufferedReader(new InputStreamReader(client.getInputStream()));
os= new DataOutputStream (client.getOutputStream());
}catch(IOException e){
e.printStackTrace();
}
}
#Override
public void run() {
while(true){
try {
tempReceived = is.readLine();
MainServer.ritorni.append(tempReceived);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
my only problem is that the interface get freezed after i click the start button.
You have your Server running on the UI thread:
if(button.getText() == "Avvia"){
System.out.print("Server avviato");
Thread server = new Server();
System.out.print("Server avviato");
server.start(); // <- not run()
System.out.print("Server avviato");
}
Related
so here is my code :
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
class Server implements Runnable{
Socket connectionSocket;
public static Vector clients=new Vector();
public Server(Socket s){
try{
System.out.println("Client Got Connected " );
connectionSocket=s;
}catch(Exception e){e.printStackTrace();}
}
public void run(){
try{
BufferedReader reader =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
clients.add(writer);
while(true){
String data1 = reader.readLine().trim();
System.out.println("Received : "+data1);
for (int i=0;i<clients.size();i++){
try{
BufferedWriter bw= (BufferedWriter)clients.get(i);
bw.write(data1);
bw.write("\r\n");
bw.flush();
}catch(Exception e){e.printStackTrace();}
}
}
}catch(Exception e){e.printStackTrace();}
}
public static void main(String argv[]) throws Exception{
System.out.println("Threaded Chat Server is Running " );
ServerSocket mysocket = new ServerSocket(5555);
while(true){
Socket sock = mysocket.accept();
Server server=new Server(sock);
Thread serverThread=new Thread(server);
serverThread.start();
}
}
}
mychat.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class mychat implements Runnable
{
public JTextField tx;
public JTextArea ta;
public String login="Imed";
BufferedWriter writer;
BufferedReader reader;
public mychat(String l)
{
login=l;
ClientName z = new ClientName();
JFrame f=new JFrame(z.getName()+"'s Chat");
f.setSize(400,400);
JPanel p1=new JPanel();
p1.setLayout(new BorderLayout());
JPanel p2=new JPanel();
p2.setLayout(new BorderLayout());
tx=new JTextField();
p1.add(tx, BorderLayout.CENTER);
JButton b1=new JButton("Send");
p1.add(b1, BorderLayout.EAST);
ta=new JTextArea();
p2.add(ta, BorderLayout.CENTER);
p2.add(p1, BorderLayout.SOUTH);
f.setContentPane(p2);
try
{
Socket socketClient= new Socket("localhost",5555);
writer= new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
reader =new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
}
catch(Exception e){e.printStackTrace();}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
String s=login+" : "+tx.getText();
tx.setText("");
try
{
writer.write(s);
writer.write("\r\n");
writer.flush();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
);
f.setVisible(true);
}
public void run()
{
try
{
String serverMsg="";
while((serverMsg = reader.readLine()) != null)
{
System.out.println("from server: " + serverMsg);
ta.append(serverMsg+"\n");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
startclient.java
public class startclient
{
public static void main(String [] args)
{
try
{
ClientName n = new ClientName();
mychat c=new mychat(n.getName());
Thread t1=new Thread(c);
t1.start();
}
catch(Exception e){e.printStackTrace();}
}
}
And last ClientName.java
import java.util.*;
public class ClientName
{
String name;
public String getName()
{
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name : ");
name = sc.nextLine();
return name;
}
}
So basically, i want to limit how many client that could join my server(which maximum is 10 client). And if there is another client that want to join the server after it is full, that client will be rejected so it cannot joined.
I think that's it, though if there are any other improvement in other areas at my code it will also be appreciated. Sorry for my bad english
*Oh and sorry since I forget to include it, but somehow when I start the client, it ask the name twice
You can fix main method in your server and add sayGoodBye() as follows:
private static final int CONNECTION_LIMIT = 10;
public static void main(String argv[]) throws Exception {
System.out.println("Threaded Chat Server is Running ");
ServerSocket mysocket = new ServerSocket(5555);
int socketCount = 0;
while (true) {
Socket sock = mysocket.accept();
Server server = new Server(sock);
if (socketCount++ < CONNECTION_LIMIT) {
Thread serverThread = new Thread(server);
serverThread.start();
} else {
// without starting a thread and notifying only new client
server.sayGoodbye();
}
}
}
public void sayGoodbye() throws IOException {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()))) {
writer.write("Sorry, new client connections are not accepted, bye for now");
} catch (Exception e) {
e.printStackTrace();
}
connectionSocket.close();
}
I have these following code for communication between client and server. I can run client and server within same machine. But if I am trying to run client from a different machine I cant run. Also I need another client so that this 2 clients can chat with each other through server.
Now server and client can exchange data among each other. But I want another client so that only this 2 clients can exchanging data among themselves through the server.
Client.java
public class Clin extends JFrame{
private JLabel statuslabel,chatlabel,instruction,instruction1;
private JTextArea statusarea;
private JPanel chatbox;
private JScrollPane statusscroll;
private JButton Embed,Send,Decode;
private Socket connection;
private ObjectInputStream input;
private ObjectOutputStream output;
private JCheckBox []checks;
private BufferedImage[] images;
private ButtonGroup grp;
private String ServerIP;
public BufferedImage Bufim;
public Clin cli;
public JLabel setlabel;
private int JC;
private String security=null;
public Clin(String host){
super("Client");
Bufim=null;
cli=this;
JC=-1;
ServerIP=host;
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(720,20,700,700);
this.setResizable(false);
this.setLayout(null);
this.getContentPane().setBackground(Color.RED);
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
Clin cli=new Clin("localhost");
cli.startRunning();
}
public void startRunning(){//////////////////////////////
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\nClient terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeConnection();
}
}
private void connectToServer() throws IOException{
showMessage("\nAttempting connection...");
connection = new Socket(InetAddress.getByName(ServerIP), 7777);
showMessage("\nConnection Established! Connected to: " +
connection.getInetAddress().getHostName());
}
private void setupStreams() throws
IOException{//////////////////////////////////////////////////
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are now setup");
}
private void whileChatting() throws
IOException{///////////////////////////////////
ableToSend(true);
Object mess=null;
try {
showMessage("\n" + (String)input.readObject());
security=JOptionPane.showInputDialog(this,"Hey Client please
provide the OTP you just recieved!");
if(security==null){
security="-";
}
sendMessage(security);
String rs=(String)input.readObject();
showMessage("\n" + ((rs.equals("CLOSE"))?"":rs));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Clin.class.getName()).log(Level.SEVERE,
null, ex);
}
do{
try{
mess =input.readObject();
if(mess instanceof String){
if(!((String)mess).equals("CLOSE"))
showMessage("\n" + mess);
}
else {
ByteArrayInputStream bin=new
ByteArrayInputStream((byte[]) mess);
BufferedImage ms=ImageIO.read(bin);
displayMessage(ms);
bin.close();
}
}catch(Exception Ex){
showMessage("\nThe server has sent an unknown object!");
}
}while(mess instanceof byte[]||(mess!=null&&!
((String)mess).equals("CLOSE")));
}
server.java
public class Serv extends JFrame{
private JLabel statuslabel,chatlabel,instruction,instruction1;
private JTextArea statusarea;
private JPanel chatbox;
private JScrollPane statusscroll,scroll;
private JButton Embed,Send,Decode;
private ServerSocket server;
private Socket connection;
private ObjectInputStream input;
private ObjectOutputStream output;
private JCheckBox []checks;
private BufferedImage[] images;
private ButtonGroup grp;
public BufferedImage Bufim;
public Serv sser;
public JLabel setlabel;
private int JC;
private String security=null;
public Serv(){
super("Server");
Bufim=null;
sser=this;
JC=-1;
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(10,20,700,700);
this.setResizable(false);
this.setLayout(null);
this.getContentPane().setBackground(Color.RED);
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
Serv ser=new Serv();
ser.startRunning();
}
public void startRunning(){//////////////////////////////
try{
server = new ServerSocket(7777,100);
while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(Exception eofException){
showMessage("\nServer ended the connection!");
} finally{
closeConnection();
}
}
} catch (IOException ioException){
ioException.printStackTrace();
}
}
private void waitForConnection() throws
IOException{/////////////////////////////////////
showMessage("\nWaiting for someone to connect...");
connection = server.accept();
showMessage("\nNow connected to " +
connection.getInetAddress().getHostName());
}
private void setupStreams() throws
IOException{//////////////////////////////////////////////////
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are now setup");
}
private void whileChatting() throws
IOException{///////////////////////////////////
chatbox.removeAll();
this.repaint();
this.validate();
String s=JOptionPane.showInputDialog(this,"Hey Server please
set the OTP for Client!");
if(s.equals("")){
s="12345";
}
double dd;
while((dd=Math.random())<0.1){}
Integer xx=(int)(dd*100000);
//String s=xx.toString();
security=s;
String message = " You are now connected!\n Your OTP : "+s;
sendMessage(message);
try {
String ss=(String)input.readObject();
if(!ss.equals(security)){
sendMessage("Incorrect OTP !");
return;
}
else sendMessage("Verification Successfull !");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Clin.class.getName()).log(Level.SEVERE,
null, ex);
}
ableToSend(true);
Object mess=null;
do{
try{
mess =input.readObject();
if(mess instanceof String){
if(!((String)mess).equals("CLOSE"))
showMessage("\n" + mess);
}
else {
ByteArrayInputStream bin=new ByteArrayInputStream((byte[]) mess);
BufferedImage ms=ImageIO.read(bin);
displayMessage(ms);
bin.close();
}
}catch(Exception Ex){
showMessage("\nThe user has sent an unknown object!");
}
}while(mess instanceof byte[]||(mess!=null&&!((String)mess).equals("CLOSE")));
}
i'm trying to create a chat application using multhitreading functionalities and here's the code of the session class that handles connections and of the server class that accept connections:
Session class:
public class Session extends Thread{
Socket Sock;
BufferedReader din;
PrintWriter dout;
Thread receive;
Server serv;
boolean connected = false;
String lineSep = System.getProperty("line.separator");
public Session(Socket s, Server n){
super("ThreadSessions");
this.Sock = s;
this.serv = n;
}
public void run(){
try{
din = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
dout = new PrintWriter(Sock.getOutputStream());
connected = true;
Receive();
}
catch(IOException ioe){
ioe.printStackTrace();
}
receive.start();
}
public void sendTo(String text){
dout.write(text);
dout.flush();
}
public void sendToAll(String text){
for(int ind = 0; ind < serv.sessions.size(); ind++){
Session s = serv.sessions.get(ind);
s.sendToAll(text);
}
}
public void Receive(){
receive = new Thread(new Runnable(){
#Override
public void run() {
receive = new Thread(new Runnable(){
String msgIn;
public void run() {
while(connected){
try{
msgIn = din.readLine();
if(msgIn != "" || msgIn != null){
System.out.println(msgIn);
msgIn = "";
}else{
}
}
catch(SocketException exc){
exc.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
});
}
}
Server class:
public class Server {
private JFrame frame;
private JTextField txtPort;
JTextArea textArea, textSessions;
String lineSep = System.getProperty("line.separator");
ServerSocket ServSock;
Socket Sock;
String port;
public JTextField textField;
int numbSess = 0, actSess = 0;
ArrayList<Session> sessions = new ArrayList<Session>();
boolean shouldRun = true;
public static void main(String[] args)
{
Server window = new Server();
window.frame.setVisible(true);
}
public Server() {
initializeComponents(); //This void initializes the graphic components
}
private void Connect(){
port = txtPort.getText();
int portN = 0;
try{
portN = Integer.parseInt(port);
}
catch(NumberFormatException exc)
{
exc.printStackTrace();
}
try{
ServSock = new ServerSocket(9081);
while(shouldRun){
Sock = ServSock.accept();
String ip = Sock.getInetAddress().getHostAddress();
Session s = new Session(Sock, this);
s.start();
sessions.add(s);
numbSess++;
}
}
catch(Exception exc){
exc.printStackTrace();
System.exit(3);
}
}
private void initializeComponents() {
[...]
Button btnConn = new JButton("Open Connection");
btnConn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connect();
}
});
btnConn.setBackground(new Color(0, 0, 0));
btnConn.setForeground(new Color(0, 128, 0));
btnConn.setBounds(160, 13, 137, 25);
frame.getContentPane().add(btnConn);
[...]
}
What i want to do is creating a chat application that can handle more connection at the same time but instead of entering the first connection(session in my app.) it continues waiting for other connections and adding those in the arrayList.
Probably the code is full of mistakes so forgive me.
If somebody knows a better way to create a server that can handle more client's connections those are welcome.
Hope someone can help me, thanks in advance.
instead of entering the first connection(session in my app.) it continues waiting for other connections and adding those in the arrayList
This is due to how your threads are set up
Each time you make and start a session, its run method is called...
public void run()
{
Receive();
[...]
receive.start();
}
...which in turn sets up receive in Receive();
public void Receive()
{
receive = new Thread(new Runnable()
{
public void run()
{
receive = new Thread(new Runnable()
{
public void run()
{
//your actual code that you wanted to run
}
});
}
});
}
The thread created when ran, will do one thing, set up receive yet again, with the code you wanted the first time
receive = new Thread(new Runnable()
{
public void run()
{
//your actual code that you wanted to run
}
});
But after you call Receive();, you only called receive.start(); once
You'll either need to call it twice, and somehow ensure that it updated in time, or just remove the excess thread
I am building an application on Socket programming in swing in which server listens for clients and if a client is connected I want
A button should be added for each client if connected on server screen
Add a listener on each button.For example add Send Message function for each client
I have created a thread in server which listens for client connections but I can not add jbutton at runtime.
Please reply.
Is that what you need ? :
import javax.swing.*;
import java.awt.event.*;
public class NewButtonOnRunTime {
static JPanel panel;
static JFrame frame;
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame = new JFrame("Add Buttons");
JButton button = new JButton("Simulate new Client");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JButton jb = new JButton("A new Client");
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This is an button action");
}
});
panel.add(jb);
frame.revalidate();
}
});
panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Assuming you already have some kind of isConnected bool,
if(isConnected){
JButton runTimeButton = new JButton();
runTimeButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//do all the things you need to do in here,
//alternatively, define this inner class somewhere else and pass in
// an instance of it
}
});
frame.add(runTimeButton);
}
Based on ServerSocket communication in java (i.e. TCP), if a client is connected to the server with a particular port say 5555, no other clients will not be able to connect to the server with the same port at the same time because the port is already in use. So, each client should be using different port if you want to get simultaneous communication with the clients.
Look at this sample code, it adds JButton at runtime when a new client is connected :
(run client code and server code in separate machine connected together)
Server code
package com.test.socket;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class ServerFrame extends JFrame {
private Map<Integer, SocketVO> serverSocketMap;
private int startingPort = 5555;
public ServerFrame() {
}
public ServerFrame(String title) {
super(title);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setLayout(new FlowLayout());
initComponents();
serverSocketMap = new HashMap<Integer, SocketVO>();
keepStartServerSocket();
setVisible(true);
}
private JTextArea area = null;
private void initComponents() {
area = new JTextArea(20, 20);
add(area);
// addDynamicButton();
}
private void addDynamicButton(final int port) {
JButton button = new JButton("Client on " + port + " port");
add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Socket socket = serverSocketMap.get(port).getSocket();
try {
String content = area.getText();
socket.getOutputStream().write(content.getBytes());
System.out.println("seding text area content to " + port);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class SocketVO {
private ServerSocket serverSocket;
private Socket socket;
public ServerSocket getServerSocket() {
return serverSocket;
}
public void setServerSocket(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
}
private void keepStartServerSocket() {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
System.out.println("waiting for a client at port "
+ startingPort);
openServerSocket(startingPort);
startingPort++;
}
}
}).start();
}
private void openServerSocket(final int port) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
final Socket socket = serverSocket.accept();
SocketVO socketVO = new SocketVO();
socketVO.setServerSocket(serverSocket);
socketVO.setSocket(socket);
serverSocketMap.put(port, socketVO);
addDynamicButton(port);
checkForCosing(port, socket);
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkForCosing(final int port, final Socket socket) {
new Thread(new Runnable() {
#Override
public void run() {
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] b = new byte[1024];
int read = 0;
try {
StringBuilder builder = new StringBuilder();
while ((read = inputStream.read(b)) != -1) {
builder.append(new String(b));
}
if (builder.toString().equals("close")) {
closeServerSocket(port);
System.out.println("server port " + port + " closed");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
/**
* the method to close corresponding sockets
*
* #param port
*/
private void closeServerSocket(int port) {
Socket socket = serverSocketMap.get(port).getSocket();
ServerSocket serverSocket = serverSocketMap.get(port).getServerSocket();
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ServerFrame("Server Socket Frame");
}
}
Client code :
package com.test.socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private int startingPort = 5550;
private void bindToServer() {
while(true) {
try {
Socket socket = new Socket("127.0.0.1", startingPort);
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] b = new byte[1024];
int read = 0;
try {
StringBuilder builder = new StringBuilder();
while((read = inputStream.read(b)) != -1) {
builder.append(new String(b));
}
System.out.println("message from server : "+builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
startingPort++;
}
if (startingPort == 5580) {
}
}
}
public static void main(String[] args) {
new Client().bindToServer();
}
}
As per your last comment:
I have tested the program with two clients. The server is connected to two clients successfully. But buttons are not added at runtime for each client.
You are able to connect with multiple client and you have added a button also but it's not visible on the server.
Calling validate() again on JFrame will solve your problem after adding new JButton.
public class Test extends JFrame {
private JButton field[];
public JButton[] getField() {
return field;
}
public void test(int n) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
field = new JButton[n];
for (int i = 0; i < field.length; i++) {
field[i] = new JButton("" + i + "");
field[i].addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("clicked button");
}
});
panel.add(field[i]);
}
add(panel);
}
public static void main(String[] args) {
Test test = new Test();
test.setSize(300, 300);
test.setVisible(true);
test.setLocationRelativeTo(null);
test.test(5);
}
}
I have a client-server communication code. but, I actually want multiple clients communicating with the server not other clients, how should I implement it?
// This is server code:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ServerFile extends JFrame {
private JTextField usertext;
private JTextArea chatwindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
public ServerFile() {
super("Admin");
usertext = new JTextField();
usertext.setEditable(false);
usertext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendmessage(event.getActionCommand());
usertext.setText("");
}
});
add(usertext, BorderLayout.SOUTH);
chatwindow = new JTextArea();
add(new JScrollPane(chatwindow));
setSize(300, 250);
setVisible(true);
}
public void startrunning() {
try {
server = new ServerSocket(6789, 100);
while (true) {
try {
waitForConnection();
setupstream();
whilechatting();
} catch (Exception e) {
System.out
.println("\nYou have an error in conversation with client");
} finally {
closecrap();
}
}
} catch (Exception e) {
System.out.println("\nYou have an error in connecting with client");
}
}
private void waitForConnection() throws IOException {
showmessage("\nWaiting for someone to connect");
connection = server.accept();
showmessage("\nNow connected to "
+ connection.getInetAddress().getHostName());
}
private void setupstream() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showmessage("\nStreams are setup");
}
private void whilechatting() throws IOException {
String message = "\nYou are now connected ";
sendmessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
showmessage(message);
} catch (Exception e) {
System.out.println("\nError in reading message");
}
} while (!message.equals("CLIENT-END"));
}
private void closecrap() {
showmessage("\nClosing connection");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (Exception e) {
System.out.println("\nError in closing server");
}
}
private void sendmessage(String message) {
try {
chatwindow.append("\nSERVER: " + message);
output.writeObject("\nSERVER: " + message);
output.flush();
} catch (Exception e) {
chatwindow.append("\nError in sending message from server side");
}
}
private void showmessage(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatwindow.append("\n" + text);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
usertext.setEditable(tof);
}
});
}
}
public class Server {
public static void main(String args[]) {
ServerFile server1 = new ServerFile();
server1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
server1.startrunning();
}
}
// and this is the client code:
import javax.swing.JFrame;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ClientFile extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField usertext;
private JTextArea chatwindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message="";
private String serverIP;
private ServerSocket server;
private Socket connection;
public ClientFile(String host)
{
super("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.SOUTH);
chatwindow= new JTextArea();
add(new JScrollPane(chatwindow));
setSize(300,250);
setVisible(true);
}
public void startrunning() {
try {
connecttoserver();
setupstream();
whilechatting();
}
catch(Exception e){
System.out.println("\nYou have an error in coversation with server");
}
finally{
closecrap();
}
}
private void connecttoserver() throws IOException{
showmessage("\nAttempting connection");
connection = new Socket(InetAddress.getByName("127.0.0.1"),6789);
showmessage("\nConnected to "+connection.getInetAddress().getHostName());
}
private void setupstream() throws IOException{
output= new ObjectOutputStream(connection.getOutputStream());
output.flush();
input= new ObjectInputStream(connection.getInputStream());
showmessage("\nStreams are good to go");
}
private void whilechatting()throws IOException{
ableToType(true);
do {
try{
message = (String)input.readObject();
showmessage(message);
}
catch(Exception e){
System.out.println("\nError in writing message");
}
} while(!message.equals("SERVER - END"));
}
private void closecrap(){
showmessage("\nClosing....");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}
catch(Exception e){
System.out.println("\nError in closing client");
}
}
private void sendmessage(String message){
try{
chatwindow.append("\nCLIENT: "+message);
output.writeObject("\nCLIENT: "+message);
output.flush();
}
catch(Exception e){
chatwindow.append("\nError in sending message from client side");
}
}
private void showmessage(final String m){
SwingUtilities.invokeLater( new Runnable(){
public void run(){
chatwindow.append("\n"+m);
}});
}
private void ableToType(final boolean tof){
SwingUtilities.invokeLater( new Runnable(){
public void run(){
usertext.setEditable(tof);
}});
}
}
public class Client {
public static void main(String args[])
{
ClientFile obj2= new ClientFile("127.0.0.1");
obj2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj2.startrunning();
}
}
Applying multithreading is a good solution, but when I applied, there gets connection extablished between only one client and one server.. Please help me to do this
Applying multithreading is a good solution, but when I applied, there gets connection extablished between only one client and one server.. Please help me to do this
I did not get through (and thus checked) all your code, but I noticed one thing:
in your startrunning() function you:
create a server socket
in an infine loop:
wait for a new connection
when there's a new connection call setupstream()
and chat using whilechatting()
so there, you will get only one new connection that will get its stream set up and chat. You can only have one thread serving your clients, so only the first one arrived will get served, until it releases the thread so another can connect.
You should instead do:
create a server socket
in an infine loop:
wait for a new connection
when there's a new connection:
create a new thread for that connection
call setupstream()
and chat using whilechatting()
There each client will get spawned into their own cosy thread, while the main thread is in its infinite loop waiting for new clients.
HTH