How can i put my class in the client in socket programming? - java

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);

Related

How to publish socket server in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I want to publish my socket server on a Window host or another for my project. However, I could not find how to do this because I could not find any examples. There is Server and Client in here, but I will use server one. Client just for testing it. And also this code can run in the Windows terminal. It is a good point. Please help me how can I solve it?
Server.JAVA
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(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 "Stop" is sent
while (!line.equals("Stop"))
{
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[])
{
Server server = new Server( 5000);
}
}
Client.java
import java.net.*;
import java.io.*;
public class Client
{
// 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 Client(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);
}
// string to read message from input
String line = "";
// keep reading until "Stop" is input
while (!line.equals("Stop"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
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[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
There's no such thing as "publish". Just run your server. That's it. Now clients can connect to it.
If there is a firewall between your client and server, then you'll have to configure the firewall appropriately. If you're on a network with private addresses (typical home LAN setup) then you'll have to arrange port forwarding in the NAT box ('router').

Exampels on a Server-Client-Chat applikation on JAVA [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I have been "googeling" around for a long time for examples over Server-client-chat application, but I can't really understand them. Many of them are using a class and creates the GUI from it, and I don't want to copy straight from it. Alot of examples doesn't either really explain how you send messages from a client to the server and then it sends the message out to all the other clients.
I am using NetBeans and I was wondering if there is some good tutourials or examples that can help me with this?
Here comes the multiThreading program :) the server has two classes, and client has one. Hope you Like it!
SERVER MAIN CLASS:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
int MAXCLIENTS = 20;
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
// An array of clientsConnected instances
ClientThread[] clientsConnected = new ClientThread[MAXCLIENTS];
try {
server = new ServerSocket(port);
System.out.println("listening on port: " + port);
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
clientSocket = server.accept();
} catch (IOException e) {
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
System.out.println("Client connected!");
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c] == null){
// if it is empty ( null) then start a new Thread, and pass the socket and the object of itself as parameter
(clientsConnected[c] = new ClientThread(clientSocket, clientsConnected)).start();
break; // have to break, else it will start 20 threads when the first client connects :P
}
}
}
}
}
SERVER CLIENT CLASS:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ClientThread extends Thread{
private ClientThread[] clientsConnected;
private Socket socket = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private String clientName = null;
//Constructor
public ClientThread(Socket socket, ClientThread[] clientsConnected){
this.socket = socket;
this.clientsConnected = clientsConnected;
}
public void run(){
try {
// Streams :)
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String message = null;
clientName = in.readUTF();
while (true){
message = in.readUTF();
for (int c = 0; c < clientsConnected.length; c++){
if (clientsConnected[c]!= null && clientsConnected[c].clientName != this.clientName){ //dont send message to your self ;)
clientsConnected[c].sendMessage(message, clientName); // loops through all the list and calls the objects sendMessage method.
}
}
}
} catch (IOException e) {
System.out.println("Client disconnected!");
this.clientsConnected = null;
}
}
// Every instance of this class ( the client ) will have this method.
private void sendMessage(String mess, String name){
try {
out.writeUTF(name + " says: " + mess);
} catch (IOException e) {
e.printStackTrace();
}
}
}
AND FINALLY THE CLIENT:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
Main m = new Main();
m.connect();
}
public void connect() throws IOException{
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
System.out.print("Enter your name: ");
String name = keyboard.nextLine();
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//start a thread which will start listening for messages
new ReceiveMessage(in).start();
// send the name to the server!
out.writeUTF(name);
while (true){
//Write messages :)
String message = keyboard.nextLine();
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
class ReceiveMessage extends Thread{
DataInputStream in;
ReceiveMessage(DataInputStream in){
this.in = in;
}
public void run(){
String message;
while (true){
try {
message = in.readUTF();
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I ran the server in eclipse, and started two clients from the CMD, looks like this:
Here is a super simple I made just now with some comments of what is going on. The client connects to the server can can type messages which the server will print out. This is not a chat program since the server receives messages, and the client send them. But hopefully you will understand better it better :)
Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static DataInputStream in;
public static DataOutputStream out;
public static void main(String[] args) throws IOException {
int port = 4444;
ServerSocket server = null;
Socket clientSocket = null;
try {
//start listening on port
server = new ServerSocket(port);
System.out.println("Listening on port: " + port);
//Accept client
clientSocket = server.accept();
System.out.println("client Connected!");
//initialize streams so we can send message
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
String message = null;
while (true) {
// as soon as a message is being received, print it out!
message = in.readUTF();
System.out.println(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!server.isClosed()){server.close();}
if (!clientSocket.isClosed()){clientSocket.close();}
}
}
}
Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
//declare a scanner so we can write a message
Scanner keyboard = new Scanner(System.in);
// localhost ip
String ip = "127.0.0.1";
int port = 4444;
Socket socket = null;
try {
//connect
socket = new Socket(ip, port);
//initialize streams
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while (true){
System.out.print("\nMessage to server: ");
//Write a message :)
String message = keyboard.nextLine();
//Send it to the server which will just print it out
out.writeUTF(message);
}
}
catch (IOException e){
e.printStackTrace();
if (!socket.isClosed()){socket.close();}
}
}
}

Java Client Server Chat Program

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.

Multithreaded Client Server Proxy java

I am currently implementing a multithreaded proxy server in java which will accept messages from clients and forward them to another server which will then acknowledge the reception of the message. However, i'm having trouble doing so. Could someone point out what i am doing wrong? Thanks.
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client{
public static void main(String[] args)
{
try
{
Socket client = new Socket(InetAddress.getLocalHost(), 6789);
if(client.isBound())
{
System.out.println("Successfully connected on port 6789");
}
Scanner scanner = new Scanner(System.in);
DataInputStream inFromProxy = new DataInputStream(client.getInputStream());
DataOutputStream outToProxy = new DataOutputStream(client.getOutputStream());
while(true)
{
String message;
System.out.print("Enter your message: ");
message = scanner.next();
outToProxy.writeUTF(message);
System.out.println(inFromProxy.readUTF());
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
System.exit(2);
}
}
}
The server code Server.java:
import java.io.*;
import java.net.*;
/**
* the client send a String to the server the server returns it in UPPERCASE thats all
*/
public class Server {
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(6780);
if(server.isBound())
{
System.out.println("Server successfully connected on port 6780");
}
Socket client = null;
while(true)
{
client = server.accept();
if(client.isConnected())
{
System.out.println("Proxy is connected");
}
DataInputStream inFromProxy = new DataInputStream(client.getInputStream());
DataOutputStream outToProxy = new DataOutputStream(client.getOutputStream());
System.out.println(inFromProxy.readUTF());
outToProxy.writeUTF("Message has been acknowledged!");
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
System.exit(2);
}
}
}
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class Proxy{
public static ServerSocket server = null;
public static Socket client = null;
public static void main(String[] args)
{
try
{
server = new ServerSocket(6789);
Socket clientsocket = null;
while(true)
{
client = server.accept();
if(client.isConnected())
{
System.out.println("Proxy is currently listening to client on port 6789");
}
clientsocket = new Socket(InetAddress.getLocalHost(), 6780);
Thread t1 = new ProxyHandler(client, clientsocket);
t1.start();
if(clientsocket.isBound())
{
System.out.println("Clientsocket successfully connected on port 6780");
}
Thread t2 = new ProxyHandler(clientsocket, client);
t2.start();
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
}
}
}
The Proxy code is:
import java.io.*;
import java.net.*;
public class ProxyHandler extends Thread {
private Socket socket;
private String message;
public ProxyHandler(Socket socket, Socket clientsocket)
{
this.socket = socket;
}
public void run()
{
message = "";
try
{
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while(true)
{
message = in.readUTF();
out.writeUTF(message);
System.out.println(message);
}
}
catch(IOException io)
{
System.err.println("IOException: " + io.getMessage());
System.exit(2);
}
}
}
There is no multithreading here. There should be. Each accepted socket should be entirely processed in its own thread, in both the server and the proxy.
There is no point in testing isBound() immediately after creating and connecting a Socket. It will never be false.
There is no point in testing isConnected() immediately after an accept(). It will never be false.
The server must close each accepted socket once it is finished with it, i.e. once it has EOS from it (read() returns -1).
The proxy must also close each accepted socket once it is finished with it, ditto.
A proxy of any kind should just copy bytes. It shouldn't make assumptions about the format of the data. Don't use readUTF(), use count = read(byte[]) and write(buffer, 0, count). That also means that you don't need DataInput/OutputStreams in the proxy.

java.io.StreamCorruptedException: invalid stream header: 72657175

Hey I am implementing an electronic voting system based on client server chat.
When I run the server it runs without any problems but without printing as well and also the client. But as soon as I give the input to the client, it gives me the following exception and crashes. Here is the code of the server and the client. So what do u think I should do to start the engine?
package engine;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
public class Server {
ServerSocket server;
int port = 6000;
public Server() {
try {
server = new ServerSocket(6000);
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleConnection(){
try {
while(true){
Socket connectionSocket;
connectionSocket = server.accept();
new ConnectionHandler(connectionSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.handleConnection();
}
}
class ConnectionHandler implements Runnable {
Socket connectionSocket;
Calendar votingStartTime;
Calendar votingEndTime;
boolean timeUp;
ObjectInputStream inFromClient;
ObjectOutputStream outToClient;
BufferedWriter outToFile;
BufferedReader inFromAdmin;
ArrayList<SingleClient> clients = new ArrayList<SingleClient>();
ArrayList<Candidate> candidates;
this is the part of the code the Exception comes from:
public ConnectionHandler(Socket socket) {
try {
this.connectionSocket = socket;
votingStartTime = new GregorianCalendar();
outToClient = new ObjectOutputStream(
connectionSocket.getOutputStream());
inFromClient = new ObjectInputStream(
connectionSocket.getInputStream());
inFromAdmin = new BufferedReader(new InputStreamReader(System.in));
startVotingSession();
Thread t = new Thread(this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
and this is the client's main method the Exception as soon as i give the input:
public static void main(String[] args) throws Exception {
client c = new client();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
while(true){
input = br.readLine();
if(input.equals("0")){
c.register();
}else if(input.equals("1")){
c.login();
}else if(input.equals("2")){
c.listCandidates();
}else if(input.equals("3")){
c.vote();
}else if(input.equals("4")){
c.checkResults();
}else if(input.equals("5")){
c.checkFinalResults();
}else if(input.equals("6")){
c.logout();
}else {
break;
}
}
}
}
without seeing the relevant code, i would guess you are recreating the ObjectInputStream on an existing socket InputStream. you must create the object streams once per socket and re-use them until you are completely finished with the socket connection. also, you should always flush the ObjectOutputStream immediately after creation to avoid deadlock.

Categories

Resources