problems with sending String via socket in java - java

hi everyone i have problems with sending 2 strings via socket in java.
i have UI that get Username and password from client and send it to server . my problem make 2 part :1-i can not get the string username in my server 2- when the client send the username the socket is close before send the password here is my code please help me .
the main purpose is getting 2 string username and password from UI (client)and send them by socket to server.
Server:
package finalproject;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
ServerSocket listener;
Socket socket;
OutputStream out ;
InputStream in;;
InputStreamReader reader;
OutputStreamWriter writer;
String massage;
public void connectserver() throws IOException
{
listener = new ServerSocket(9097);
System.out.println("Server is running on port 9097 ...");
}
public void waitforclient() throws IOException
{
socket = listener.accept();
System.out.println("A new client connected to the server");
}
public void startstreamsserver() throws IOException
{
in = socket.getInputStream();
out = socket.getOutputStream();
writer = new OutputStreamWriter(out);
reader = new InputStreamReader(in);
System.out.println("Server streams are ready");
}
public void closestreamsserver() throws IOException
{
writer.close();
reader.close();
}
public void getinfoserver() throws IOException
{
try
{
reader.read();
System.out.println(reader);
System.out.println("input is : " + reader.toString());
}
catch(IOException IOE)
{
IOE.printStackTrace();//if there is an error, print it out
}
}
}
Client:
package finalproject;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Client
{
Socket socket;
OutputStream out1;
InputStream in1;
OutputStreamWriter writer;
InputStreamReader reader;
String massage;
JFrame frame;
BorderLayout blayout;
JButton center;
JButton south;
FlowLayout fLoyout;
JLabel jb1;
JTextField name;
JLabel jb2;
JTextField pass;
JLabel jb7;
JPanel cpanel;
JPanel spanel;
public void connectclient() throws IOException
{
socket = new Socket("localhost", 9097);
System.out.println("connect to server on port 9097");
}
public void startstreamsclient() throws IOException
{
in1 = socket.getInputStream();
out1 = socket.getOutputStream();
writer = new OutputStreamWriter(out1);
reader = new InputStreamReader(in1);
System.out.println("Client streams are ready");
}
public void closestreamsclient() throws IOException
{
writer.close();
reader.close();
}
public void loginformclient()
{
frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
blayout = new BorderLayout();
center = new JButton();
south = new JButton();
frame.setLayout(blayout);
fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
jb1 = new JLabel("Username :");
name = new JTextField(20);
center.add(jb1);
center.add(name);
jb2 = new JLabel("Password :");
pass = new JTextField(30);
center.add(jb2);
center.add(pass);
jb7 = new JLabel("Save");
south.add(jb7);
cpanel = new JPanel();
cpanel.add(center);
spanel = new JPanel();
south.addActionListener((ActionEvent ae) -> {
try
{
writer.write(name.getText());
writer.flush();
writer.write(pass.getText());
writer.flush();
writer.close();
}
catch (IOException ex)
{
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
});
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
frame.add(cpanel, BorderLayout.CENTER);
frame.add(spanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
and my main class :
package finalproject;
import java.io.IOException;
import javax.swing.JFrame;
public class Finalproject
{
public static void main(String[] args) throws IOException
{
//build Server & Client
Server server = new Server();
Client client = new Client();
//Start Server & Client
server.connectserver();
client.connectclient();
//Server wait for new connection
server.waitforclient();
//start the Streams
client.startstreamsclient();
server.startstreamsserver();
//Client send login information to Server
client.loginformclient();
//Server get information
server.getinfoserver();
}
}
but the my inputs in my server are:
java.io.InputStreamReader#171fc7e
input is : java.io.InputStreamReader#171fc7e

Edited Based on EJP correct remark:
Add new line delimiter:
writer.write(name.getText() + System.lineSeparator());
writer.write(pass.getText());
writer.flush();
replace this:
reader = new InputStreamReader(in);
System.out.println("Server streams are ready");
with:
BufferedReader in = new BufferedReader(reader);
String username= in.readLine();
String password = in.readLine();

Related

Buffered image is null

I am trying to send frames to java app from python app. Firstly I create a blank image on python side with numpy array and then wanna send it to java app and display it on the java side. But the bufferedimage on java side is null here is python code;
import socket
import sys
import cv2
import numpy as np
import base64
import json
from lib2to3.pytree import Leaf
from lib2to3.fixer_util import String
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "localhost"
PORT = 5555
try:
socket.connect((HOST, PORT))
except:
print "We cannot find the server !!!!"
print "Terminating the program . . ."
#exit(0)
img = np.zeros((300, 300, 3), np.uint8)
obj = NumpyEncoder()
outjson = {}
outjson['img'] = base64.b64encode(img)
outjson['leaf'] = "leaf"
json_data = json.dumps(outjson)
socket.sendall(json_data
socket.close()
and here is java side;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Base64;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.json.JSONException;
import org.json.JSONObject;
import com.sun.javafx.iio.ImageFormatDescription;
import com.sun.prism.Image;
import java.awt.Color;
import java.awt.Dimension;
public class ServerFrame extends JFrame {
private JPanel contentPane;
public static BufferedImage bufferedImage;
/**
* Launch the application.
* #throws IOException
* #throws JSONException
*/
public static void main(String[] args) throws IOException, JSONException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerFrame frame = new ServerFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(5555);
} catch(IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
System.out.println("Server Socket Has Been Started . . .");
try {
clientSocket = serverSocket.accept();
System.out.println("User Connected :" + clientSocket.getLocalAddress().toString());
} catch(IOException e) {
System.out.println(e.getMessage());
}
StringBuilder sb = new StringBuilder();
InputStream in = clientSocket.getInputStream();
if(in == null) System.exit(1);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
//System.out.println(sb.toString());
JSONObject json = new JSONObject(sb.toString());
String leaf_name = json.getString("leaf");
String mat_string = json.getString("img");
byte[] raw_data = Base64.getDecoder().decode(mat_string);
bufferedImage = ImageIO.read(new ByteArrayInputStream(raw_data));
if(bufferedImage == null) System.out.println("warning");
System.out.println(raw_data.length);
FileOutputStream fos = new FileOutputStream("image.jpg");
try {
fos.write(raw_data);
}
finally {
fos.close();
}
/*JPanel panel = new JPanel();
panel.setBackground(Color.RED);
Dimension dim = new Dimension(50,50);
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
JLabel label = new JLabel("hello");
label.setSize(label.getPreferredSize());
panel.add(label);
panel.setVisible(true);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bufferedImage)));*/
br.close();
clientSocket.close();
}
/**
* Create the frame.
*/
public ServerFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
Can you see the problem, Why is it null ?
change to :
outjson['img'] = base64.b64encode(img.tobytes())

Java Chat Application

I'm trying to make a MultiClient Chat Application in which the chat is implemented in the client window. I've tried server and client code for the same.one clint to server is running good but teo client to server is not running properly one clint communication good but second one client not giving response.
Client Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Clientchatform extends JFrame implements ActionListener {
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
String line;
BufferedReader br;
String response;
BufferedReader is ;
PrintWriter os;
public Clientchatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
Send.addActionListener(this);
conn = new Socket(InetAddress.getLocalHost(), 2000);
ChatHistory.setText("Connected to Server");
this.setTitle("Client");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
br= new BufferedReader(new InputStreamReader(System.in));
String line = is.readLine();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Server:"
+ line);
} catch (Exception e1) {
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "Me:"
+ NewMsg.getText());
try {
br= new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
ChatHistory.append(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
Clientchatform chatForm = new Clientchatform();
}
}
Server Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class serverChatform extends JFrame implements ActionListener {
static ServerSocket server;
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
//DataInputStream dis;
//DataOutputStream dos;
String line;
BufferedReader is ;
public serverChatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
this.setTitle("Server");
Send.addActionListener(this);
server = new ServerSocket(2000, 1, InetAddress.getLocalHost());
ChatHistory.setText("Waiting for Client");
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter os=new PrintWriter(conn.getOutputStream());
line=is.readLine();
ChatHistory.append(ChatHistory.getText() + 'n' + "Client:"
+ line);
} catch (Exception e1)
{
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "ME:"
+ NewMsg.getText());
try {
PrintWriter os =new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
}
You're definitely on the right track, but I've got a question for you to ask yourself.
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
How often is this code executed? Consider that of course the main(),
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
is only called once, and therefore only one serverChatform will ever be created.
As you seem to have written quite a bit of code yourself, and it therefore seems like you're ready to learn more, I'm not going to give a full solution, but merely a direction.
Once you accept a client, with conn = server.accept();, you will have to create another new serverChatform();. This has to happen in a different Thread though. How to do this, I leave as an exercise for you.
Each connected client has to be served in its own thread. Additionally you need a Thread that continiously listens for new clients to connect. That would look like this.
List<Socket> clients; // Save the socket for each client
[...]
new Thread(new Runnable(){
#Override
public void run() {
// Thread that runs forever listening for new clients
while(true){
Socket conn = server.accept();
// new client has connected, store its socket
clients.add(conn);
// and start new thread that interacts with this new client
new Thread(new Runnable(){
#Override
public void run() {
// SERVE CLIENT HERE!
}
}).start();
}
}
}).start();

Multi-client chat program, broadcasting chat to all clients?

I'm trying to make a very simple chat program that can accommodate multiple clients. I have a multi-threaded server and can connect multiple clients to it, but the server only communicates with a single client (as it should, each client is on its own thread) I need help getting the server to send all messages from all connected clients to each client. I think I'd need to share a single object between threads? Here's the code:
server:
import java.net.ServerSocket;
import java.net.Socket;
public class ThreadedCommandServer {
public static void main(String[] args) throws Exception {
System.out.println("Starting server....");
int port = 8989;
ServerSocket ss = new ServerSocket(port);
while(true) {
System.out.println("Waiting for connection from client...");
Socket socket = ss.accept();
ServerThread st = new ServerThread(socket);
st.start();
}
}
}
server thread:
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket socket = null;
private String s;
public ServerThread(Socket s) {
socket = s;
}
public void run() {
try {
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
s = (String) ois.readObject();
System.out.println("received string: " + s);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(s);
System.out.println("sent object back to client...");
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
client:
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Controller {
private ClientFrame cf;
private String message;
private Socket socket;
private String response;
public Controller(ClientFrame cf) {
this.cf = cf;
}
public void sendChat(String s) {
message = s;
System.out.println("FROM CONTROLLER: received: " + message);
try {
InetAddress i = InetAddress.getByName("localhost");
socket= new Socket(i, 8989);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
System.out.println("FROM CONTROLLER: sending message to the server...");
oos.writeObject(message);
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
System.out.println("getting string back from server....");
response = (String) ois.readObject();
cf.updateGUI(response);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
GUI:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientFrame extends JFrame {
private JTextArea chatArea;
private JTextField type;
private JButton submit;
private JPanel upper;
private JPanel lower;
private BorderLayout bl;
JScrollPane jsp;
Controller c;
public ClientFrame() {
bl = new BorderLayout();
upper = new JPanel();
lower = new JPanel();
chatArea = new JTextArea("chat goes here", 20, 30);
c = new Controller(this);
chatArea.setEditable(false);
chatArea.setLineWrap(true);
type = new JTextField("type here", 20);
jsp = new JScrollPane(chatArea);
new SmartScroller(jsp);
lower.add(type);
submit = new JButton("send");
submit.addActionListener(new Submit());
type.addActionListener(new Submit());
lower.add(submit);
upper.add(jsp);
this.setSize(400, 600);
this.setLayout(bl);
this.setTitle("MattChatt");
this.add(upper, BorderLayout.NORTH);
this.add(lower, BorderLayout.SOUTH);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void updateGUI(String s) {
chatArea.append("\n" + s);
}
private class Submit implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (type.getText().equals("")) {
System.out.println("no text entered");
} else {
System.out.println("submitted");
c.sendChat(type.getText());
type.setText("");
}
}
}
}
You have no way of accessing all of the ServerThreads you create.
What you need to do is group them all together in a collection, such as an ArrayList.
Or even better, a HashMap, if you would ever want to expand your application to allow private messaging, you would need to access a specific ServerThread, and with a HashMap you can do so easily.
Anyways... when it is time to send out the message, you should loop your collection through and send the message to the OutputStreams associated with each ServerThread.

I am doing a multiclient chat sever program in java. But I am not able to run it. Here is my code for multi client server

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import javax.swing.*;
/* The code is able to run single client but not multiple client. When I run this program with my client class it is able to handle only one client. While I run multiple threads it lost its communication with the first thread. I don't know why. */
public class MultipleChatClient extends JFrame{
Vector<HandleAClient> clients = new Vector<HandleAClient>();
JButton btnSend = null;
JButton btnExit = null;
JTextArea taMessages = null;
JTextField tfInput = null;
BufferedReader br = null;
PrintWriter pw = null;
ServerSocket server = null;
Socket socket = null;
int clientNumber = 0;
public MultipleChatClient(){
this.Interface(); /* creates GUI */
try{
server = new ServerSocket(8900);
while(true){
socket = server.accept();
HandleAClient task = new HandleAClient(socket); /* add every client to vector */
clients.add(task);
new Thread(task).start();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
public class HandleAClient implements Runnable{ /* multithreaded class to handle multiclients */
private Socket socket;
public HandleAClient(Socket socket){
clientNumber++;
this.socket = socket;
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(), true);
while(true){
String line = br.readLine();
taMessages.append("Client Number " + clientNumber + " said: ");
taMessages.append(line + "\n");
}
}
catch(IOException ex){
ex.printStackTrace();
}
catch(Exception e){
taMessages.append("Connection Lost");
}
}
public void sendMessage() {
pw.println(tfInput.getText());
}
}
public void Interface(){ /* to build GUI */
setLayout(new BorderLayout());
btnSend = new JButton("Send");
btnExit = new JButton("Exit");
taMessages = new JTextArea();
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);
tfInput = new JTextField(50);
JPanel but = new JPanel(new GridLayout(2,1,5,10));
but.add(btnSend);
but.add(btnExit);
JScrollPane sp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(sp,"Ce`enter code here`nter");
JPanel bp = new JPanel(new BorderLayout());
bp.add(tfInput, BorderLayout.CENTER);
bp.add(but, BorderLayout.EAST);
add(bp, BorderLayout.SOUTH);
btnSend.addActionListener(new buttonListner());
//btnSend.addKeyListener(new buttonListner());
btnExit.addActionListener(new buttonListner());
setSize(600,600);
setTitle("Server");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
//pack();
}
public class buttonListner implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnExit){
System.exit(1);
}
else{
taMessages.append("You Said: ");
taMessages.append(tfInput.getText() + "\n");
for(HandleAClient c: clients){
c.sendMessage();
}
tfInput.setText(null);
}
}
}
public static void main(String[] args) {
new MultipleChatClient();
}
}
You have to use Multi-threading. Create a new Thread for each client connected to the server.
I have already posted some of the samples in the same context.
Please have a look at below posts. It might help you to understand it.
Java Server with Multiclient communication.
Multiple clients access the server concurrently

Android Client/Server Socket client not receiving

I am at this with ages and the problem i am having is simple i am not able to print out the data from the server to client everything else is working just that when the server sends a message to the client the phone it never gets or prints it out any insight or help would be great and i am getting no errors
client
package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
new Incomingdata().execute();
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{ System.out.println("Test123");
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
System.out.println("Test1234");
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
System.out.println("Test1235");
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Server
package handy_server.simple_gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//imports for server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Pandaboy
*/
class ServerGUI extends JFrame implements ActionListener
{
private Socket connection;
private InetAddress ip;
private JTextField t1 = new JTextField(null);
private JTextField t2 = new JTextField(null);
private JTextField t3 = new JTextField(null);
private JButton b2 = new JButton("Send");
private JButton b1 = new JButton("Working");
private JPanel p1 = new JPanel();
private ServerSocket listeningSocket;
private int port= 0;
private ArrayList<Contact> myContacts = new ArrayList<Contact>();
//-------------------------serverGui------------------------------------------------------------
public ServerGUI(int port){
this.port = port;
init();
}
public void init()
{
Container content = getContentPane();
content.setLayout(new FlowLayout());
Font f = new Font("TimesRoman", Font.BOLD, 20);
p1.setLayout(new GridLayout(2, 2));
content.add(p1);
p1.add(t1);
p1.add(b1);
p1.add(t2);
p1.add(t3);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(210, 300);
setVisible(true);
System.out.println("Just about to start the server...");
startServer();
}
public void actionPerformed(ActionEvent e)
{
Object target = e.getSource();
if (target == b1)
{
t1.setText("Button working");
MyHelpers.buildConversations(this, myContacts);
}
if(target == b2)
{
t1.setText("button working2");
String number = t2.getText();
int phone_length = number.length();
if (phone_length <= 20)
{
for(int a=1; a <=(20 - phone_length); a++ )
{
number += " ";
}
}
String msg = t3.getText();
String text = "7"+number+msg;
System.out.print(""+text);
OutputStream o = null;
try
{
o = connection.getOutputStream();
}
catch (IOException ex)
{
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------startServer------------------------------------------------------------
private void startServer()
{
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground()
{
System.out.println("in startserver...");
try
{
listeningSocket = new ServerSocket(port);
try
{
ip = InetAddress.getLocalHost();
System.out.println("Please enter this in your phone " + ip.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
while (true)
{
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
InputStream in = connection.getInputStream();
Scanner r = new Scanner(in);
OutputStream o = connection.getOutputStream();
PrintWriter p = new PrintWriter(o);
String message = r.nextLine();
System.out.println("" + message);
t1.setText(message);
// get the message type
// 0 sms 1 contact 2 incoming call
System.out.println(message);
if(message.startsWith("0"))
{
System.out.println(message);
String type = message.substring(1,2);
int theType = Integer.parseInt( type );
String number = message.substring(7, 21).trim();
String theText = message.substring(21);
String theName = MyHelpers.getName(number, myContacts);
System.out.println("Number = "+number);
System.out.println("Sender = "+theName);
System.out.println("Text = "+theText);
Contact cRef = MyHelpers.getContactReference(number, myContacts);
if (cRef != null)
{
cRef.addsms(theType, theName, theText);
}
}
if(message.startsWith("1"))
{
System.out.println(message);
String name = message.substring(1, 31).trim();
String pnumber = message.substring(31, 51).trim();
String email = message.substring(51, 91).trim();
myContacts.add(new Contact(name, pnumber, email));
System.out.println( name + pnumber + email);
}
if(message.startsWith("2"))
{
String unkown = message.substring(0, 1).trim();
String number = message.substring(1, 14).trim();
String theName = MyHelpers.getName(number, myContacts);
System.out.println(""+unkown+""+theName+" Is calling you");
}
if(message.startsWith("5"))
{
System.exit(0);
}
Any Help would be great i am stumped by this
In your server append '\n' to the end of the response so change this
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
to this:
PrintWriter p = new PrintWriter(o);
p.println(text + "\n");
p.flush();
System.out.print("text sent"+text);
i think the reason it hangs is because readLine() is looking for '\n' and it never recieves it
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}

Categories