Is it possible to write a client-server code that can connect 2-different computers to play a multi-player game using sockets in java? Do these computers need to be connected by a cable? Or can I send the data through some other source? (Like internet..) Or is it enough if I know just the ip addresses of both computers and put that in in the sockets? Please tell me how I can do it.
You can connect computers that are on the same Wifi network. You will need to open a server and then open clients that connect to it.
The following code may help:
Server.java
ArrayList<Socket> clientSockets = new ArrayList<>();
try {
ServerSocket serverSocket = new ServerSocket(port); // port same as client
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("Server opened at: "+inetAddress.getHostAddress());
while (true) // this keeps the server listening
{
final Socket socket = serverSocket.accept(); // this accepts incomming connections
clientSockets.add(socket); // adds current connection to an arraylist
System.out.println(timestamp()+"Connection from "+socket.getInetAddress());
Thread t = new Thread(new Runnable() // Thread handles messages sent by client that just connected
{
#Override
public void run() {
try
{
while (socket.isConnected())
{
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromClient = br.readLine();
if (fromClient != null)
{
//use message from client
}
else // connection might have been reset by client
{
socket.close();
clientSockets.remove(socket);
}
}
} catch (SocketException e)
{
System.out.println("Disconnection from "+socket.getInetAddress());
} catch (IOException e) {}
}
});
t.start();
}
} catch (Exception e) {}
Client.java - add two buttons, one for connecting and one for sending
bConnect.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
InetAddress address = InetAddress.getByName(host); // host IPaddress
socket = new Socket(address, port); // port same as server
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
final Timer time = new Timer(); // to get new server txt if it changes
TimerTask t = new TimerTask() {
#Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String kry = br.readLine();
// use message from server
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "The Server has just gone offline");
}
}
};
time.scheduleAtFixedRate(t, 0, 2000);
}
catch (Exception e1)
{e1.printStackTrace();
JOptionPane.showMessageDialog(null, "The Server is not online");}
}
});
bSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String textGekry = "what you are sending";
if (!textGekry.equals(""))
{
String sendMessage = textGekry + "\n";
try
{
bw.write(sendMessage);
bw.flush();
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(null,"The Server is most likely offline");
}
}
}
});
Related
I have a server app written in C# for Windows. I have a client app for android. I want to send data continuously from client to server in an infinite loop. The data is being sent but sometimes, there is a bad delay. I'm really stuck at it. Here's my client side code:
new Thread(new Runnable() {
public void run() {
Socket socket = null;
PrintWriter out = null;
while(true) {
try {
socket = new Socket(IP, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
out.println(msg);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
Any idea why is there a delay?
Your problem is that you are initializing the socket every single iteration of your while loop.
new Thread(new Runnable() {
public void run() {
Socket socket = null;
PrintWriter out = null;
while(true) {
try {
socket = new Socket(IP, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
out.println(msg);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
Refactor it out of the loop, like this:
new Thread(new Runnable() {
public void run() {
Socket socket = new Socket(IP, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true) {
try {
out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}).start();
Unless that is by design, in which case, why?
It seems the code is correct. The lag may be caused not only by the application but also by the network status.
Try to ping to the router from both devices and see if you are having lag spikes due to the wireless conection. If you see high lag in pings the problem is in the connection, not in the application.
I'm creating chat program. At first, I send message to server from client and server should get message, but the message is not sent to the server until I shut down client.
Here is my code:
Client:
private Socket Client;
private Thread RunClient;
private JButton Send;
private int Port=8000;
private String Host="localhost";
public void init() {//Here we connecting to server
Send=new JButton();
Send.setFont(new Font("Times New Roman", Font.BOLD, 15));
Send.setLocation(575,Text.getHeight()+15);//395
Send.SetBorderColor(Color.cyan);
Send.setForeground(Color.white);
Send.setText("Send");
Send.setSize(30,70);
Send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SendButton_Click(e);
}
});
try
{
InetAddress address = InetAddress.getByName(Host);
Client = new Socket(address, Port);
System.out.println("Client started. Port: "+Port+"\n");
}catch(Exception e){
System.out.println("Error:"+e);
}
}
public void SendButton_Click(ActionEvent e) {//Here we sending message to server
String sendMessage = "hi";
try {
sendMessageToServer(Client,sendMessage);//sending message to server
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("Message sent to the server : "+sendMessage);
}
}
private void sendMessageToServer(Socket socket,String message) throws IOException {
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream()));
writer.write(message);
writer.flush();
}
Here is server:
private int Port=8000;
public void init() {//Here we starting server and starting thread
try {
serverSocket = new ServerSocket(Port);
System.out.println("Server on. Port: "+Port+"\n");
} catch (IOException e1) {
e1.printStackTrace();
}
RunServer = new Thread() {
public void run() {
ServerLoop();
}
};
RunServer.start();
}
public void ServerLoop() {//here we should receive message..
while(true) {
System.out.println("Server loop");
try
{
Socket clientSocket = serverSocket.accept();
InputStreamReader inputstreamreader = new
InputStreamReader(clientSocket.getInputStream());
BufferedReader bufferedreader = new
BufferedReader(inputstreamreader);
PrintWriter printwriter = new
PrintWriter(clientSocket.getOutputStream(),true);
String line = "";
boolean done = false;
while (((line = bufferedreader.readLine()) != null) &&(!done)){
System.out.println("Received from Client: " + line);
if (line.compareToIgnoreCase("Exit") == 0) done = true;
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Your server is waiting for a full line, i.e. a String that is terminated with \r, \n, or both. Your client does not send a line ending, thus the server's call to readLine() cannot complete until the stream ends, when the remaining (non-line-terminated) input is returned.
Try sending "hi\n" and it should work.
The readLine() method will wait until it receives a newline character (\n) before returning. This means that the method blocks until the client is disconnected. The solution is simple; change the line in sendMessageToServer() that is
writer.write(message);
to
writer.write(message + "\n");
However, you will not be able to send the server messages containing \n without bugs. To do so, you will have to rewrite your reading code to use character-by-character reading.
i've done a socket programming with client residing on android and server residing on the desktop ....... whenever server is down as we know client lost the connection.....so it undergoes a looping until it connects to server.......
here the problem is in the below code
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
in the while loop in the case of lost connection.........but when the connection is on it again creates a new object........
can anyone please tell me how to solve this problem..........
In the client side
while(true){
try {
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
try
{
if((line = in.nextLine())!=null)
{
// my task to be done
}
}catch(Exception d){
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"+tabletclient.isConnected());
}
} catch (UnknownHostException e) { System.out.println("Entered 2.........");
} catch (IOException e) { System.out.println("Entered 3.........");e.printStackTrace();
}
}
In in the Server side
:
:
private Set <Socket> TABhs=new HashSet<Socket>();
:
:
new Thread(new TABServerThread()).start(); // runs in background
:
:
:
class ServerThread implements Runnable {
private ServerSocket server;
#Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
System.out.println("Server Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
System.out.println("Server Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static PrintWriter out;
class ClientHandler implements Runnable {
private Socket clientSocket;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
System.out.println("ClientHandlerThread Start communication with : "+ clientSocket.getLocalAddress());
try{
while((line = in.nextLine()) != null) {
System.out.println("ClientHandlerThread Client says: " + line);
String dat[]=line.split("#");
String query="insert into table_orders (tableno,kotno, orders,status) values('"+dat[1]+"','"+dat[0]+"','"+dat[2]+"','pending')";
try {
int i= dbGetDet.insertDetails(query);
if(i>0)
{
fillTable();
filtercomboBox();
out.print("success");
out.flush();
for(Socket so:TABhs)
{
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableallocation#"+dat[1]);
ot.flush();
}
System.out.println("SENDED 'SUCCESS' TO CLIENT");
}
} catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
// }
}
}catch(Exception r){}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the Button click of server
String stat=status_combo.getSelectedItem().toString();
String tables=tableno_combo.getSelectedItem().toString();
String kotno=kotno_combo.getSelectedItem().toString();
if(stat.equals("Processing"))
{
try {
TABhs = new CopyOnWriteArraySet(TABhs);
int soint=1;
System.out.println("TABhs Processing--------------------->"+TABhs.size());
for(Iterator <Socket> it=TABhs.iterator();it.hasNext();)
{
Socket so=it.next();
System.out.println("SEEE SOCKET Processing"+soint+"----->"+so.isClosed());
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableupdate#"+tables+"#"+kotno+"#processing");
ot.flush();
JOptionPane.showMessageDialog(rootPane, "<html><body>Table Kot Status Changed to <b>Processing</b></body></html>");
soint++;
}
System.out.println("TABhs Processing--------------------->"+TABhs.size());
}
catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOW EACH TIME WHEN BUTTON IS CLICKED THE OUTPUT IS AS GIVEN BELOW
FISRT CLICK
SEEE SOCKET Ready 1----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 2----->false
TABhs--------------------->2
SECOND CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 3----->false
TABhs--------------------->4
FOURTH CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
SEEE SOCKET Ready 3----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 4----->false
TABhs--------------------->5
I think the problem is at the client's side you read a line and then create a new connection.
I think you must keep reading the socket until it's closed or an error occurs.
For example:
while (true)
{
tabletclient = null;
int loop = 0;
// loop until a connection is established
while (tabletclient == null)
{
try
{
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
}
catch (Exception e)
{
e.printStackTrace();
// set the value to quit when no connection could be established
if (loop++ > 100)
return;
}
}
try
{
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
// read the socket until it's closed or an error occurs
try
{
while ((line = in.nextLine()) != null)
{
// my task to be done
}
}
catch (Exception d)
{
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"
+ tabletclient.isConnected());
}
tabletsocket.close();
}
catch (UnknownHostException e)
{
System.out.println("Entered 2.........");
}
catch (IOException e)
{
System.out.println("Entered 3.........");
e.printStackTrace();
}
}
Also, you must close the server side when the transfer from the server to the client is completed.
This may be a stupid question, but here goes.
Im writing this chat program, where there is a server, and clients that can connect to it. I want to implement private messaging into the program, but I don't know how to get the clients to directly connect to eachother. For the server, I used a ServerSocket, which runs on a single port. To get that to work, I needed to forward a port to the server. Is there a way to get the clients to wait for connections, without forwarding a port to them?
Thanks
The whole point of TCP/IP is that a single client connects to a predefined port on a server. So yes, you'll also need to have a ServerSocket on the client that's going to accept the direct connection. You'll almost always run into trouble with port forwarding and the like, which is why UPnP was invented one day.
What you are trying to do is 'peer to peer' connectivity, aka P2P, which is always, by its very definition, plagued by firewalling problems. As such it's usually, especially for a chat, easier to use the central server as 'switchboard' server and relay the private messages as well.
I've written not long time ago a template for multiple client - server application, that might help you to solve your problem. The rest of your question was already answerd by #Niels, I think ;)
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
I am using a server socket in linux and I need to close it and reopen before the time_wait TCP status expires. I set the reuse address option of the server socket before the binding but it still throws a BindException.
I also tried this http://meteatamel.wordpress.com/2010/12/01/socket-reuseaddress-property-and-linux/ but it still doesn't work.
To open a server socket i use:
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345));
and to close:
ss.close();
The "Address already in use" BindException is throwed at the bind call.
This code generates the exception:
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
#Override
public void run() {
try {
final ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345));
Socket s = ss.accept();
System.out.println((char) s.getInputStream().read());
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(500);
Socket s = new Socket("localhost", 12345);
s.getOutputStream().write('c');
}
You set reuse before binding not after you get an exception.
ServerSocket ss = new ServerSocket(); // don't bind just yet
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345)); // can bind with reuse= true
This runs without error on Windows 7 and RHEL 5.x
for (int i = 0; i < 1000; i++) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
final ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(12345));
Socket s = ss.accept();
System.out.println((char) s.getInputStream().read());
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
Thread.sleep(50);
Socket s = new Socket("localhost", 12345);
s.getOutputStream().write('c');
t.join();
}
You have to do that: it means extract the code so that it does not recur constantly
public class....
private ServerSocket socServer;
onCreate
...
try {
socServer = new ServerSocket();
socServer.setReuseAddress(true);
socServer.bind(new InetSocketAddress(SERVER_PORT));
} catch (IOException e) {
e.printStackTrace();
}
// New thread to listen to incoming connections
new Thread(new Runnable() {
#Override
public void run() {
try
{
// Create server side client socket reference
Socket socClient = null;
// Infinite loop will listen for client requests to connect
while (true) {
// Accept the client connection and hand over communication
// to server side client socket
socClient = socServer.accept();
// For each client new instance of AsyncTask will be created
ServerAsyncTask serverAsyncTask = new ServerAsyncTask();
// Start the AsyncTask execution
// Accepted client socket object will pass as the parameter
serverAsyncTask.execute(new Socket[] {socClient});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();