How I compile my server code on server? - java

I am new in socket programming.
i have two java programs( Client.java and Server.java), For socket programming i want to compile my server.java code to server which always listen to socket, But i don't know what i do on server.
Server.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) {
String data = "Toobie ornaught toobie";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Client.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}

Search on how to compile Java files. In your case it will be javac Server.java to compile it, and then java Server to run. The same goes for Client.

Got it here.
http://www.careerbless.com/samplecodes/java/beginners/socket/SocketBasic1.php
Here server always listen to client.
Thank you guys for help.

Related

How do I make java sockets work? So confused

This is the code for my server, its supposed to take an input from the user, print it into console, then send it back to the user.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class DateServer {
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(10219);
Socket s = listener.accept();
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader input = new BufferedReader(in);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("connected");
out.flush();
System.out.println("connected");
String test;
while (true) {
try {
test = input.readLine();
System.out.println(test);
out.println(test + " is what I recieved");
out.flush();
} catch(Exception X) {System.out.println(X);}
}
}
}
This is the code for the client:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
public class DateClient {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws Exception {
System.out.println("Enter IP Address of a machine that is");
System.out.println("running the date service on port 10219:");
String serverAddress = keyboard.next();
Socket s = new Socket(serverAddress, 10219);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
}
}
This was designed to work across a LAN network. I have no idea why it doesn't work, all that happens is the client will get the message "connected" and nothing else will happen, no matter what is typed into the client end. I'm a noob when it comes to java, but after a bunch of googling and searching through the java libraries, I can't seem to make it work. What did I do wrong?
You send one line from the server to the client, but in your client you wait for two lines before accepting user input to be sent to the server.
Bearing in mind that input.readLine() will block until data is received, can you spot the deadlock here:
Server:
out.println("connected");
while (true) {
try {
input.readLine();
}
}
Client:
input.readLine();
while(true) {
try {
input.readLine();
out.println(keyboard.next());
}
}
(extraneous code trimmed away to show just the problematic sequence of statements)
Both your client and server mutually wait for each other trying to do input.readLine().
This can be easily seen if you remove server's out.println("connected") and its corresponding client's first input.readLine().
On the client, you should probably write first and only then read the response. Try reordering the following lines:
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
to get
out.println(keyboard.next());
out.flush();
System.out.println(input.readLine());
In the client, try changing
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
to
PrintWriter out = new PrintWriter(s.getOutputStream());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.nextLine());
out.flush();
} catch(Exception X){System.out.println(X);}
}
Your client is trying to read two lines, but your server sends just one, then polls for input, so both are locked. Also, sinc your server is reading line-by-line, your client should be sending data line-by-line.

Two-way Java chat using socket

I tried to find something similar to help me with my code and I also tried to do it by myself but I got stuck on the end and I would really appreciate if someone would help me with that.
So I have already working simple Java Client/Server code and what i want to do is to upgrade it so it can work both ways, right now after launching the server and connecting to it by the client everything what u write as a client will be shown on the server too and i want to upgrade it so what i write on the client will be shown on the server and what i write on the server will be shown on the client.
myServer.java
import java.io.*;
import java.net.*;
public class myServer {
public static void main (String[] args) {
try {
int i=0;
ServerSocket ss = new ServerSocket(9000);
System.out.println("Listening...");
Socket s = ss.accept();
System.out.println("Connection accepted");
InputStream d1 = s.getInputStream();
while ((char)i !='q')
{
i = d1.read();
System.out.print((char)i);
}
s.close();
ss.close();
} catch (Exception e) {System.out.println("Error"); }
}
}
myClient.java
import java.io.*;
import java.net.*;
public class myClient {
public static void main(String[] args) {
try {
int i=0;
Socket s=new Socket("localhost",9000);
OutputStream o = s.getOutputStream();
while ((char)i !='q')
{
i = System.in.read();
o.write((char)i);
}
s.close();
} catch(Exception e) {System.out.println("Error"); }
}
}
Thank You in advance.

Java server program doesn't accept the input from client at second run of client

I wrote a small client server program in Java. Server creates a ServerSocket on some port and keeps listening to it. Client sends some sample info to this server.
When I run Client the first time connection is accepted by server and info is printed by server. Then Client program exits. When I run Client again, connection is accepted however, data is not printed.
Please check following code.
Server Program
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(dis.available() > 0) {
System.out.println(dis.readByte());
}
}
}
}
Client Program
package javadaemon;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
} catch(IOException e) {
}
}
}
Please help me in finding why next time no data is received by server.
The reason is before server side receive data, the Client already exits, I just debug it. (Can't explain whey it works at the first time.)
Just change your code like the below, and it works.
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(true) {
try {
System.out.println(dis.readByte());
} catch (Exception e) {
break;
}
}
}
}
}
The Client must add flush before exits,
package javadaemon;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
out.flush();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Place this in your Client program after for loop:
out.flush();
out.close();
client.close();
You need to flush your stream in order to push the data forward and clean the stream. Also, you will need to close your client socket.
I just tested this successfully.

Java server / client sending array, Check in check out

Im having a little problem i have managed to send info from client to server etc... but i want to be able to do it though telnet also (Open it up and say go telnet 127.0.0.1 4444, and then put in like 1 2 3 and then it comes up in the server just like it would if sending via the client. At the moment im getting this error:
java.io.StreamCorruptedException: invalid stream header: 310D0A32
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ConnectionHandler.run(server1.java:73)
at java.lang.Thread.run(Unknown Source)
Let me know if i'm doing anything wrong please:
My main goal for this is to have it so i can enter say Username, ID and Name and then be able to recall them with a time, Like a very simple check in check out system. Would really love some help <3 :)
Client:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class client1 {
public static void main(String[] args) {
try {
// Create a connection to the server socket on the server application
Socket socket = new Socket("localhost", 7777);
// Send a message to the client application
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//oos.writeObject("A B C");
String data[]=new String[3];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter details for the array");
for(int x=0;x<3;x++){
System.out.print("Enter word number"+(x+1)+":");
data[x]=br.readLine();
}
oos.writeObject(data);
System.out.println("Details sent to server...");
oos.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class server1
{
private ServerSocket server;
private int port = 4444;
public server1()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
server1 example = new server1();
example.handleConnection();
}
public void handleConnection()
{
System.out.println("Waiting for client message got...");
// The server do a loop here to accept all connection initiated by the
// client application.
while (true)
{
try
{
Socket socket = server.accept();
new ConnectionHandler(socket);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable
{
private Socket socket;
public ConnectionHandler(Socket socket)
{
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run()
{
try
{
// Read a message sent by client application
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message[] = (String[]) ois.readObject();
//System.out.println("Message Received from client: " + message);
//b(message);
printArray(message);
ois.close();
socket.close();
System.out.println("Waiting for client message is...");
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
private void b(String message) {
List<String> list = new ArrayList<String>();
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
private void printArray(String[] arr){
for(String s:arr){
System.out.println(s);
}
}

Java client-server chat (server not receiving string)

trying to make a simple client server chat program. I've already go it so that the server reads a user input which is then sent to the client. the client then receives this and displays it. I then have the client reading the user input and sending it to the server however the server doesn't receive it. Heres my code:
Client:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Waiting for server to respond... \n");
while (!in.ready()) {}
System.out.print("Received Message: ");
System.out.println(in.readLine()); // Read one line and output it
System.out.print("\n");
//in.close();
System.out.print("Message:");
Scanner sc = new Scanner (System.in);
String data2 = sc.nextLine();
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending Message: '" + data2 + "'\n");
out.print(data2);
out.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class server {
public static void main(String args[]) {
try {
System.out.println("Waiting for client connection...");
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.println("Client has connected!\n");
System.out.print("Message:");
Scanner sc = new Scanner (System.in);
String data = sc.nextLine();
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending Message: '" + data + "'\n");
out.print(data);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
while (!in.ready()) {out.close();}
System.out.print("Received Message: ");
System.out.println(in.readLine()); // Read one line and output it
System.out.print("\n");
//in.close();
//in.close();
//out.close();
//skt.close();
//srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Both the client and the server use the same code for send/receive so I don't understand why the server won't receive.
Cheers,
Tom
print() send the text but not a new line. Try println() instead.
readLine() on the server waits for a new line, which you are not sending.
BTW: I wouldn't test for in.ready() this is more likely to be confusing than useful IMHO.

Categories

Resources