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.
Related
I made a game similar to Flappy Bird by using JavaFX. Now I want to play it by using localhost IP.
How can I move the class in FlappyBird to the client so that the flappybird becomes the client?
also how can we make multiple clients using this?
This code is a simple one i made with simple concept behind it but what i don't understand is how can i make a class as in a game of flappy bird in the socket programming. How do i implement everything from the flappy bird to the client so the client becomes a flappy bird object
Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class FlappyClient
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public FlappyClient(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
//=============
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
FlappyClient client = new FlappyClient("localhost", 5000);
}
}
````````````````````````````````````````````````
````````````````````````````````````````````````
public class FlappyServer
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public FlappyServer(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
FlappyServer server = new FlappyServer(5000);
}
}
`````````````````````````````````````````````
**The flappy bird class is too big. Lets call it FlappyBird I want to make this flappybird a client for the server**
I have found the answer
Main.main(null);
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
So this is the first Server-Client I am trying to 'setup' but it does not work as I want it to. Here is What I want:
The Client to do: (see comments in the code for the Client)
A 'user input' should be read by the Client
Send the 'user input' to the server
receive back something from the server
The server to do: (See the comments in the code for Server)
receive the 'user input' that read by the client
Do something with the 'user input'
Send what was done in (2), back to the client.
It is not working the only right thing it is doing is that it receives the input from the 'user', that is it:
public class Cli {
BufferedReader in;
PrintWriter out;
Socket s;
public Cli(int port){
try {
s = new Socket("127.0.0.1", port);
out = new PrintWriter(s.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader
(s.getInputStream()));
} catch (UnknownHostException e) {
System.out.print("fel");
} catch (IOException e) {
System.out.print("fel");
}
}
public void startaClient(){
BufferedReader stdIn = new BufferedReader (new InputStreamReader(System.in));
try {
while(true){
String userInput = stdIn.readLine();// get the user input (1)
System.out.print("from user: " + userInput);
out.write(userInput); // sends to server (2)
System.out.println(in.readLine()); // receive from server(3)
}
} catch (Exception e){
System.out.println("fel1");
}
}
public static void main(String[] args){
Cli c=new Cli(4002);
c.startaClient();
}
Here is the code for the Server:
public class Ser {
ServerSocket s;
public Ser()throws Exception{
s = new ServerSocket(4002);
}
public void startaServern()throws Exception {
while (true) {
Socket socket = s.accept(); //waits for new clients, acceptera inkommande förfrågan
Trad t = new Trad(socket);
t.start();
}
}
public static void main(String[] args)throws Exception{
Ser b = new Ser();
b.startaServern();
}
}
public class Trad extends Thread {
Socket socket;
BufferedReader in;
PrintWriter out;
public Trad(Socket s){
socket=s;
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //
out=new PrintWriter(socket.getOutputStream(),true);
}catch(Exception e){System.out.println("fel");}
}
public void run(){
while(true){
try{
String theInput = in.readLine(); //read, receive message from client (1)
String res = theInput+"blabla"; // do something with the message from the client (2)
out.write(res); // send it back to the client (3)
} catch(Exception e) {
System.out.println("fel1");
}
}
}
}
When you do readLine() it will read a line i.e. until it reaches a new line.
Unless you send a new line it will wait forever. I suggest you send a newline so the reader knows the line has ended.
Since you are using a PrintWriter the simplest solution is to use
out.println(res);
instead of out.write(res);
Goal:
My goal with this code is to create a simple web server that can handle multiple clients, and that will respond with the html to say "hi" when the client requests it.
Code:
Here's test number one. It only can handle one client once:
import java.net.*;
import java.io.*;
public class Webserver1 {
public static void main(String[] args) {
ServerSocket ss;
Socket s;
try {
//set up connection
ss = new ServerSocket(80);
s = ss.accept();
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
try (
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
DataOutputStream out = new DataOutputStream (s.getOutputStream());
) {
String inline = in.readLine();
//http request
if (inline.startsWith("GET")) {
//return http
out.writeBytes("<!doctype html><html><body><p>hi</p></body></html>");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Here's test number two. It is meant to handle multiple clients:
import java.net.*;
import java.io.*;
public class Webserver2 {
//class to handle connections
public static class server {
ServerSocket ss;
Socket s[] = new Socket[maxn];
public server () {
try {
ss = new ServerSocket(80);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public InputStream getis(int num) throws Exception {
return s[num].getInputStream();
}
public OutputStream getos(int num) throws Exception {
return s[num].getOutputStream();
}
public void close() throws Exception {
for (int i = 0; i < numc; i++) {
s[i].close();
}
}
public void newc () throws Exception {
s[numc + 1] = ss.accept();
}
}
static int numc = 0;
static final int maxn = 100;
static server se = new server();
public static void main(String[] args) {
try {
while (numc < 6) {
//set up connection, and start new thread
se.newc();
numc++;
System.out.println("0");
(new Client()).start();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static class Client extends Thread {
public void run() {
try(
BufferedReader in = new BufferedReader(new InputStreamReader(se.getis(numc)));
DataOutputStream out = new DataOutputStream (se.getos(numc));
) {
String inline;
while(true) {
inline = in.readLine();
//wait for http request
if (inline.startsWith("GET")) {
System.out.println("1");
//respond with header, and html
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Connection: close\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.writeBytes("<!doctype html><html><body><p>hi</p></body></html>");
out.flush();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
Problems:
On my computer, if I run the first example, and on my browser I type: "http://192.168.1.xxx", I get a simple "hi". However, on the second one if I try the same thing it simply doesn't work. But if in the command prompt I type: telnet 192.168.1.xxx 80, then type GET it sends back the html. Also, if I replace the DataOutputStream with a PrintWriter, it doesn't even send it to the telnet. However, I know it tries because the program prints "0" every time a connection is made, and "1" every time it prints something.
Questions:
What is the problem that prevents the browser from viewing the html?
Does it have to do with the html itself, the way I set up my connection, or the DataOutputStream?
How can I fix this?
Don't use port 80, use some other random port greater than 6000. And if you didn't close your first program properly, port 80 is still used by that program.
I used a Http server program that is similar to this. The server also creates multiple threads for each connections, so the number of clients in not limited to 100.
` public class MultiThreadServer implements Runnable {
Socket csocket;
static int portno;
static String result;
MultiThreadServer(Socket csocket)
{
this.csocket = csocket;
}
public static void main(String args[])
throws Exception
{
portno=Integer.parseInt(args[0]);
ServerSocket srvsock = new ServerSocket(portno);
System.out.println("Listening");
while (true) {
Socket sock = srvsock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run()
{
String[] inputs=new String[3];
FileInputStream fis=null;
String file=null,status=null,temp=null;
try
{
InputStreamReader ir=new InputStreamReader(csocket.getInputStream());
BufferedReader br= new BufferedReader(ir);
DataOutputStream out = new DataOutputStream(csocket.getOutputStream());
String message=br.readLine();
inputs=message.split(" ");
if(inputs[0].equals("GET"))
{
try{
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Connection: close\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.writeBytes("<!doctype html><html><body><p>hi</p></body> </html>");
}
out.flush();
fis.close();
csocket.close();
}
catch(Exception ex)
{
status="404 File not found";
os.println(status);
}
}`
This code is about client and server communication in java. I can run both codes in my PC and can connect client and server. But how will I connect 2 computers as a client and server. Here are my codes for server and client as follows:
MyServer1
//code for server
import java.io.*;
import java.net.*;
public class MyServer1
{
ServerSocket ss;
Socket s;
DataInputStream dis;
DataOutputStream dos;
public MyServer1()
{
try
{
System.out.println("Server Started");
ss=new ServerSocket(10);
s=ss.accept();
System.out.println(s);
System.out.println("CLIENT CONNECTED");
dis= new DataInputStream(s.getInputStream());
dos= new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main (String as[])
{
new MyServer1();
}
public void ServerChat() throws IOException
{
String str, s1;
do
{
str=dis.readUTF();
System.out.println("Client Message:"+str);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s1=br.readLine();
dos.writeUTF(s1);
dos.flush();
}
while(!s1.equals("bye"));
}
}
MyClient1
//code for client
import java.io.*;
import java.net.*;
public class MyClient1
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient1()
{
try
{
//s=new Socket("10.10.0.3,10");
s=new Socket("localhost",10);
System.out.println(s);
din= new DataInputStream(s.getInputStream());
dout= new DataOutputStream(s.getOutputStream());
ClientChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ClientChat() throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String s1;
do
{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message:"+din.readUTF());
}
while(!s1.equals("stop"));
}
public static void main(String as[])
{
new MyClient1();
}
}
Client Just needs the IP of the Server.You have to find out the IP of the server and tell the client about it, like:
String serverName = "IP of server comes here"; // Indicating the place to put Server's IP
s = new Socket(serverName, 10);
Server needs no change.
You have to just enter ip of the server while creating Socket Instance.
i suggest you to follow steps
1) start hotspot in any one computer which you going to use as server
2) in second computer start wifi and connect with hotspot which we just started.
3) now ho to sharing center and click on network you connect and check detail and copy dns server ip and paste it in client program