I wrote a server-client communication program and it worked well.
Client module
import java.io.*;
import java.net.*;
class Client {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
while(true){
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("myname.domain.com", 2343);
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Ready");
sentence = in.readLine();
out.writeBytes(sentence + '\n');
modifiedSentence = in.readLine();
System.out.println(modifiedSentence);
}
clientSocket.close();
}
}
Server module
import java.net.*;
public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
String cap_Sentence;
ServerSocket my_Socket = new ServerSocket(2343);
while(true) {
Socket connectionSocket = my_Socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = in.readLine();
cap_Sentence = "Raceived:" + clientSentence + '\n';
out.writeBytes(cap_Sentence);
}
}
}
The above is the code for a single client - server communication, now I want multiple client to interact with that server. I googled for it and found that it can be done with the use of a thread for each single client to talk to the server, but since I am a beginner I don't know exactly how to implement. So somebody please tell me how to do or give me some idea about it.
MainServer class
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(2343);
} catch (IOException e) {
System.err.println("Could not listen on port: 2343");
}
while(listeningSocket){
Socket clientSocket = serverSocket.accept();
MiniServer mini = new MiniServer(clientSocket);
mini.start();
}
serverSocket.close();
}
}
Helper Class
public class MiniServer extends Thread{
private Socket socket = null;
public MiniServer(Socket socket) {
super("MiniServer");
this.socket = socket;
}
public void run(){
//Read input and process here
}
//implement your methods here
}
You want to look into Java concurrency. That's the concept of one Java program doing multiple things at once. At a high level you will be taking your while(true) { //... } block and running it as part of the run() method of a class implementing Runnable. You'll create instances of Thread that invoke that run() method, probably one per client you expect.
For a really good, deep understanding of all that Java offers when it comes to concurrency, check out Java Concurrency in Practice.
Well, when I do something like that, I implement a listener that manages the server side, so when a client (the client won't probably need changes) connects, the server launch one thread to work with that client.
while (!stop)
{
socket = serverSocket.accept();
HiloSocket hiloSocket = new HiloSocket(socket, this);
hiloSocket.start();
}
Of course, HiloSocket extends Thread and it has the logic behind to manage the client...
Related
I want to edit this code, so it could accept more client join on my server. This server is just used to accept one client's connection, and it can send, and receive messages. But I want to make it a "Multiplayer" Server. Many clients connected to one server. Here's the Server side code, and the Client side code:
I would really appreciate your help!
My Server Code:
import java.net.*;
import java.lang.*;
public class RecordAppServer {
public static void main(String[] args) throws IOException {
final int port = 8136;
System.out.println("Server waiting for connection on port "+port);
ServerSocket ss = new ServerSocket(port);
Socket clientSocket = ss.accept();
System.out.println("Recieved connection from "+clientSocket.getInetAddress()+" on port "+clientSocket.getPort());
//create two threads to send and recieve from client
RecieveFromClientThread recieve = new RecieveFromClientThread(clientSocket);
Thread thread = new Thread(recieve);
thread.start();
SendToClientThread send = new SendToClientThread(clientSocket);
Thread thread2 = new Thread(send);
thread2.start();
}}
class RecieveFromClientThread implements Runnable
{
Socket clientSocket=null;
BufferedReader brBufferedReader = null;
public RecieveFromClientThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
}//end constructor
public void run() {
try{
brBufferedReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
String messageString;
while(true){
while((messageString = brBufferedReader.readLine())!= null){//assign message from client to messageString
if(messageString.equals("EXIT"))
{
break;//break to close socket if EXIT
}
System.out.println("From Client: " + messageString);//print the message from client
//System.out.println("Please enter something to send back to client..");
}
this.clientSocket.close();
System.exit(0);
}
}
catch(Exception ex){System.out.println(ex.getMessage());}
}
}//end class RecieveFromClientThread
class SendToClientThread implements Runnable
{
PrintWriter pwPrintWriter;
Socket clientSock = null;
public SendToClientThread(Socket clientSock)
{
this.clientSock = clientSock;
}
public void run() {
try{
pwPrintWriter =new PrintWriter(new OutputStreamWriter(this.clientSock.getOutputStream()));//get outputstream
while(true)
{
String msgToClientString = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));//get userinput
msgToClientString = input.readLine();//get message to send to client
pwPrintWriter.println(msgToClientString);//send message to client with PrintWriter
pwPrintWriter.flush();//flush the PrintWriter
//System.out.println("Please enter something to send back to client..");
}//end while
}
catch(Exception ex){System.out.println(ex.getMessage());}
}//end run
}//end class SendToClientThread
My Client Code:
import java.io.*;
import java.net.*;
public class RecordAppClient {
public static void main(String[] args)
{
try {
Socket sock = new Socket("192.168.0.2",8136);
SendThread sendThread = new SendThread(sock);
Thread thread = new Thread(sendThread);thread.start();
RecieveThread recieveThread = new RecieveThread(sock);
Thread thread2 =new Thread(recieveThread);thread2.start();
} catch (Exception e) {System.out.println(e.getMessage());}
}
}
class RecieveThread implements Runnable
{
Socket sock=null;
BufferedReader recieve=null;
public RecieveThread(Socket sock) {
this.sock = sock;
}//end constructor
public void run() {
try{
recieve = new BufferedReader(new InputStreamReader(this.sock.getInputStream()));//get inputstream
String msgRecieved = null;
while((msgRecieved = recieve.readLine())!= null)
{
System.out.println("From Server: " + msgRecieved);
//System.out.println("Please enter something to send to server..");
}
}catch(Exception e){System.out.println(e.getMessage());}
}//end run
}//end class recievethread
class SendThread implements Runnable
{
Socket sock=null;
PrintWriter print=null;
BufferedReader brinput=null;
public SendThread(Socket sock)
{
this.sock = sock;
}//end constructor
public void run(){
try{
if(sock.isConnected())
{
System.out.println("Client connected to "+sock.getInetAddress() + " on port "+sock.getPort());
this.print = new PrintWriter(sock.getOutputStream(), true);
while(true){
//System.out.println("Type your message to send to server..type 'EXIT' to exit");
brinput = new BufferedReader(new InputStreamReader(System.in));
String msgtoServerString=null;
msgtoServerString = brinput.readLine();
this.print.println(msgtoServerString);
this.print.flush();
if(msgtoServerString.equals("EXIT"))
break;
}//end while
sock.close();}}catch(Exception e){System.out.println(e.getMessage());}
}//end run method
}//end class
You'll need to implement a multithreaded server.
The general structure will be the following:
while(true) {
1) Wait for client requests (Socket client = server.accept();)
2) Create a thread with the client socket as parameter
a) The new thread creates I/O streams (just like youre doing
with the PrintWriter and BufferedReader objects)
b) Communicate with client (in your example -
brBufferedReader.readLine())
3) Remove thread once the service is provided.
}
I suggest you take a look at the Oracle documentation:
https://www.oracle.com/technetwork/java/socket-140484.html#multi
This might also be useful:
http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html
I am making a client to client chatting application in Java and I wanted to know how I could create Sockets on demand. More specifically, I wanted to know if there is any method which checks whether there is an incoming connection. Using that I could have two methods running simultaneously together with Threads with one method waiting for a connection while the other handles the server (messages being sent). Is this a fine strategy or should I use a different technique?
What if I used a Socket Array and added a new Socket to it with each connection?
Would the array however cause a problem when referencing to Sockets later on?
The if has a && with nothing as I want to add a method there which will help me check whether there is an incoming connection or not.
import java.util.*;
import java.io.*;
import java.net.*;
public class Server {
public static ServerSocket SSock;
public static Socket Sock;
public static DataInputStream dis;
public static DataOutputStream dos;
public static PrintWriter pw;
public static BufferedReader br;
public static Socket[] wow;
public int counter = 0;
public int port = 2500;
public Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException{
SSock = new ServerSocket();
Sock = SSock.accept();
dis = new DataInputStream(Sock.getInputStream());
dos = new DataOutputStream(Sock.getOutputStream());
pw = new PrintWriter(dos, true);
br = new BufferedReader(new InputStreamReader(dis));
Server s = new Server();
Thread t1 = new Thread(s.new connection());
Thread t2 = new Thread(s.new server());
t1.start();
t2.start();
}
public class connection implements Runnable {
public void run() {
try {
Thread.sleep(200);
} catch (Exception e) {
//NOTHING!! MWAH MWAH MWAH
//Sigh. I'll add something here later...
}
if ( && Sock.isConnected()) {
}
}
}
public class server implements Runnable{
public void run() {
}
}
}
I think you have somehow misunderstood the concept of TCP sockets. When you try to initiate a connection to remote server it does not “create demand;” the server has to listen on the socket before you initiate the request, otherwise you will only get a “connection refused” error.
In Java, ServerSocket.accept() handles all that for you: it listens for incoming connections and as soon as a connection has been established, it returns you the Socket that you use for all further communication on this particular connection.
I figured it out I have to make a method which returns a socket.
public Socket s (Socket so) { //When I add a Socket to an arraylist, I call this method
//edit properties
return so;
}
Guys am sick of this client and server chat program plz help me
my program is compiled and runing but the problem is that when i trying to pass the msg to the server its not working it pass by itself..now what correction i do...
Server Code:
import java.io.*;
import java.net.*;
class serv
{
ServerSocket s;
Socket c;
DataInputStream dis;
DataOutputStream dos;
BufferedReader disi;
public serv()
{
try
{
s = new ServerSocket(2000,0,InetAddress.getLocalHost());
System.out.println("Server is Created");
c = s.accept();
System.out.println("Request Accepted");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void talk()throws IOException,UnknownHostException
{
dis = new DataInputStream(c.getInputStream());
dos = new DataOutputStream(c.getOutputStream());
disi = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str = new String(disi.readLine());
dos.writeUTF(str);
System.out.println(str);
}
}
public static void main(String args[])
{
try
{
serv c = new serv();
c.talk();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client Code:
import java.io.*;
import java.net.*;
class clien
{
Socket c;
DataInputStream dis;
BufferedReader disi;
DataOutputStream dos;
public clien()throws IOException,UnknownHostException
{
c=new Socket(InetAddress.getLocalHost(),2000);
System.out.println("Request is sended");
}
public void talk()throws IOException,UnknownHostException
{
try
{
dis=new DataInputStream(c.getInputStream());
dos=new DataOutputStream(c.getOutputStream());
disi=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str=new String(disi.readLine());
dos.writeUTF(str);
System.out.println(str);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
try
{
clien c=new clien();
c.talk();
}
catch(Exception e){ }
}
}
There are tons of problems.
It seems as if you're trying to do some kind of protocol like this:
Client connects to server
Client sends message to server
Server receives message
A peer-to-peer type system. Not sure if you're expecting the server to be seen as another client (you type messages into it to send it to the client), but the problem is that right when the connection establishes, both Client and Server go into a loop. In this loop, there's only 1 thing you can focus on.
Client:
main(String[]) -> connect -> read input from user (loop)
start program -> connect -> start listening for info from server
Server:
main(String[]) -> accept connection -> read input from user (loop)
If you want your client to receive info from the server and be able to send info aswell, you need 2 threads.
static Socket s;
static DataOutputStream out;
static DataInputStream in;
public static void main(String[] args) {
try {
s = new Socket("host", 2000);
out = new DataOutputStream(s.getOutputStream());
in = new DataInputStream(s.getInputStream());
new Thread(new Runnable() {
public void run() {
Scanner scanner = new Scanner(System.in);
String input;
while(!(input = scanner.nextLine()).equals("EXITPROGRAM")) {
out.writeUTF(input); //sends to client
}
}
}).start();
while(true) {
String infoFromServer = in.readUTF();
//you can print to console if you want
}
}catch(Exception e) { }
}
Now, this will allow the client to receive input from the user (from the console) AND receive data from the server aswell. You can use the same structure for your server aswell if that's what you're going for.
I'm new to the network communication and I'm trying to build client-server application.
protected void init(){
Server myServer = new Server();
Client myClient = new Client();
}
That's my Client class:
public class Client {
public Client() {
init();
}
private void init() {
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
DataInputStream stdIn = new DataInputStream(System.in);
try {
echoSocket = new Socket("localhost", 1234);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
os.writeInt(stdIn.readInt());
echoSocket.getOutputStream().close();
echoSocket.getInputStream().close();
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And that's server:
public class Server {
public Server() {
init();
}
private void init() {
try {
boolean run = true;
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readInt());
s.getInputStream().close();
s.getOutputStream().close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
First of all:
Can I initialize client and server simply like i did? new Server() and new Client()?
Question 2:
Is it important what i initialize at first? client or server?
Question 3:
When i compile this code with client first initialized, i become Connection refused: connect. I know it means that there is no listening socket running on the port you are trying to connect to. That's why server must go first, i think. Is it so? can i fix it using setSoTimeout and how?
Question 4:
When i compile it with server and then client, output is nothing. And i think it has nothing to do with client, because if i try to print "1", for example, it doesn't work either. I think it just waits for the client and does nothing that goes after. How can i fix this? maybe setSoTimeout goes here too?
You can't have both client and server in the same thread.
As you already have observed, the server accepts the connection and tries to read something. It doesn't know that the client is running in the very same thread.
Either make a multi-threaded application, where client and server have their own thread. Or make two prgrams that run independently of each other. The latter would be also the "normal case".
Make two different projects, first run server than client.
Server will write on console "Server started" than run client it will ask your name, type your name press ok . Your name will be sent to server and server will reply saying hello to you.
Here is server code
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket ss= new ServerSocket(2224);
System.out.println("Serever started");
while(true)
{
Socket s=ss.accept();
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os);
String name=br.readLine();
String message="Hello "+name+"from server";
pw.println(message);
pw.flush();
}
}
catch(Exception exp)
{
System.out.println("Excepttion occured");
}
}
}
Here is client code
import java.net.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s=new Socket("localhost",2224);
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os,true);
String message = JOptionPane.showInputDialog("Give your name");
pw.println(message);
pw.flush();
String servermessage = br.readLine();
JOptionPane.showMessageDialog(null, servermessage);
s.close();
}
}
I have a java program that will connect the client to the server.
This includes making a file directory once the client had triggered the server through sending a message. For example: Once the server is running already, the client will then connect and will send a msg i.e "Your message: Lady", the server will receive a message like "Request to create a Directory named: Lady", after this a directory will be created named Lady.
But the problem is this connection is only for one-to-one. Like only one client can connect to the server...
This is the sample code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package today._;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
public class myServer {
protected static final int PORT_NUMBER = 55555;
public static void main(String args[]) {
try {
ServerSocket servsock = new ServerSocket(PORT_NUMBER);
System.out.println("Server running...");
while (true) {
Socket sock = servsock.accept();
System.out.println("Connection from: " + sock.getInetAddress());
Scanner in = new Scanner(sock.getInputStream());
PrintWriter out = new PrintWriter(sock.getOutputStream());
String request = "";
while (in.hasNext()) {
request = in.next();
System.out.println("Request to Create Directory named: " + request);
if(request.toUpperCase().equals("TIME")) {
try {
File file = new File("C:\\" + request);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
} catch (Exception e) {
System.out.println(e);
}
out.println(getTime());
out.flush();
} else {
out.println("Invalid Request...");
out.flush();
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
protected static String getTime() {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
return (dateFormat.format(date));
}
}
package today._;
import java.io.*;
import java.net.*;
import java.util.*;
public class myClient {
protected static final String HOST = "localhost";
protected static final int PORT = 55555;
protected static Socket sock;
public static void main(String args[]) {
try {
sock = new Socket(HOST,PORT);
System.out.println("Connected to " + HOST + " on port " + PORT);
Scanner response = new Scanner(sock.getInputStream());
PrintWriter request = new PrintWriter(sock.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String txt = "";
while(!txt.toUpperCase().equals("EXIT")) {
System.out.print("Your message:");
txt = in.readLine();
request.println(txt);
request.flush();
System.out.println(response.next());
}
request.close();
response.close();
in.close();
sock.close();
} catch(IOException e) {
System.out.println(e.toString());
}
}
}
Multi-client servers are generally written one of two ways:
Create a thread for each client. To do this you would create a thread to handle the calls to accept() on the server socket and then spawn a new thread to handle calls on the Socket that it returns. If you do this, you need to make sure you isolate the code for each socket as much as possible. The accept thread will loop forever, or until a flag is set, and will just call accept, spawn a thread with the new socket, and go back to calling accept. All of the work is in the child thread.
Use NIO, or another technology, to multi-plex work into 1 more more threads. NIO uses a concept sometimes called select, where your code will be called when there is input available from a specific socket.
If you are just doing a small server, you can go with the simplest design and also won't have too many clients, so I would go with #1. If you are doing a big production server, I would look into a framework like netty or jetty that will help you do #2. NIO can be tricky.
In either case, be very careful with threads and the file system, you might not get the results you expect if you don't use a Lock from the concurrency package, or synchronize, or another locking scheme.
My final advice, be careful with having a client tell a server to do anything with the file system. Just saying, that is a dangerous thing to do ;-)
Your server class must use multiple threads to handle all connections:
class MyServer {
private ServerSocket servsock;
MyServer(){
servsock = new ServerSocket(PORT_NUMBER);
}
public void waitForConnection(){
while(true){
Socket socket = servsock.accept();
doService(socket);
}
}
private void doService(Socket socket){
Thread t = new Thread(new Runnable(){
public void run(){
while(!socket.isClosed()){
Scanner in = new Scanner(sock.getInputStream());
PrintWriter out = new PrintWriter(sock.getOutputStream());
String request = "";
// and write your code
}
}
});
t.start();
}
}