public class JavaApplication15 {
public static String ip="127.0.0.1";
public static int port=5060;
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
InetAddress ii = InetAddress.getLocalHost();
System.out.println(ii);
InetAddress ad = InetAddress.getByName(ip);
System.out.println(ad);
InetAddress i = ad;
System.out.println(i);
try {
// TODO code application logic here
ss = new ServerSocket();
ss.bind(new InetSocketAddress(ip, port));
InetSocketAddress ia;
String st=ss.getLocalSocketAddress().toString(); // print socket ip and address
System.out.println(st);
System.out.println("created");
} catch (IOException ex) {
System.out.println("not created");
}
Socket client = null,ee = null;
client = ss.accept();
PrintWriter out = null;
BufferedReader in = null ;
out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while((input = in.readLine())!=null){
System.out.println(input);
System.out.println("echo :" +in.readLine());
}
out.flush();
in.close();
stdin.close();
client.close();
ss.close();
}
}
}
In this code server is being created and trying to establish a connection with socket. I think this code should show output but it is not showing. For example: if i say hello in the console , it should print hello. But it is not doing that. Can anyone help me what is actually going on here ???
Related
i want to synchronize 2 Collections with each other. If something changes at the Server side, the connected Clients get updated.
I have a quite basic question. Do I now need to copy my java project and program the server in one and the client in the other one? But that sounds like quite a lot of unnecessary work. Can't I implement it all in one project an then start server and client in one main? Do I need threads? I'm kind of stuck what the best way is here.
Thanks in advance.
Because codereview doesn't allow my code cause it's not yet working, i post it now here in the hope, that you can help me.
public class Server implements Runnable{
private String hostName = "127.0.0.1";
private int portNumber;
private ServerSocket serverSocket;
private Socket clientSocket;
public Server(int port){
this.portNumber = port;
}
public void run(){
String line = "";
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
try{
this.serverSocket = new ServerSocket(this.portNumber);
}catch (IOException e) {
System.out.println("Could not listen on port");
}
try{
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed");
}
try{
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
}catch (IOException e) {
System.out.println("Read failed");
}
while(true){
try{
line = in.readLine();
}catch (IOException e) {
System.out.println("Read failed");
}
System.out.println("line: "+line);
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
serverSocket.close();
}catch (IOException e) {
System.out.println("Could not close socket");
}
}
}
public class Client implements Runnable{
private String hostName = "127.0.0.1";
private int portNumber = 6602;
private Socket clientSocket = null;
public Client(Socket client){
this.clientSocket = client;
}
public Client(int portNumber, String hostName){
this.portNumber = portNumber;
this.hostName = hostName;
}
public void run(){
String line;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
try{
if(clientSocket == null)
this.clientSocket = new Socket(this.hostName, this.portNumber);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
out.println("Test string from client");
}catch (IOException e){
System.out.println("in or out failed");
}
}
}
public class DebugServerClient {
public static void testServerClient(){
int port = 6602;
Server srv = new Server(port);
Client clt = new Client(port, "127.0.0.1");
Thread s = new Thread(srv);
s.start();
Thread c = new Thread(clt);
c.start();
}
}
I changed it now to this and it seems to work. Is this a good way?
I have made a socket in Java.
This socket connects with a server.
When I start my program, the server sends a message that my socket is connected with the AEOS.
When I try to login to the server for sending some commands, then the server responds again with: status connected to AEOS version
This is not the message that I expect, normally my server must send a "response true".
Can you help me?
Thanks.
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
while(true) {
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
}
output socket
Why don't you try to read everything that server had sent? Also, need to open a new Socket every-time? Depends on your implementation. Try this:
public static void main(String[] args) {
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String initialMessageFromServer = null;
while ((initialMessageFromServer = inFromServer
.readLine()) != null) {
System.out.println(initialMessageFromServer);
}
while (true) {
String sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
StringBuilder modifiedSentence = new StringBuilder();
String responseFromServer = null;
while ((responseFromServer = inFromServer.readLine()) != null) {
modifiedSentence.append(responseFromServer);
modifiedSentence.append('\n');
}
System.out
.println("FROM SERVER: " + modifiedSentence.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Below is client and server program that I wrote. Now I am confused how to send ack/nack in my program.
I saw few answers on stackoverflow but i am still confused. Can you give an example of ACK/NACK in TCP protocol using java
Client:
public class Client {
public static void main(String args[]) {
try {
Socket client = new Socket("localhost", 2222);
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
Scanner input = new Scanner(System.in);
boolean a = true;
while (a) {
//receving
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(br.readLine());
if (input.equals("q")) {
a = false;
client.close();
}
pw.println("Client0: " + input.nextLine());
System.out.println(pw);
// System.out.println("Request sent successfully");
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Server:
public class Server {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Waiting for client request");
Socket client = ss.accept();
System.out.println("Accepted connection request");
Scanner input = new Scanner(System.in);
while (true) {
// receving
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
// sending
PrintStream ps = new PrintStream(client.getOutputStream());
ps.println("Server1: " + input.nextLine());
System.out.println(ps);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Thank you
Client program
public class client implements Runnable {
protected static String server_IP = "141.117.57.42";
private static final int server_Port = 5555 ;
protected static String client_IP ;
public static void main(String[] args) throws IOException{
final String host = "localhost";
int init = 0 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
client_IP = iAddress.getHostAddress();
System.out.println("Current IP address : " +client_IP);
} catch (UnknownHostException e) {
}
try {System.out.println("hello1");
Socket socket = new Socket(server_IP,server_Port);
System.out.println("hello3");
init = initialize(socket);
}catch (SocketException e) {
System.out.println("Error: Unable to connect to server port ");
}
if (init == 0 ){
System.out.println("error: Failed to initialize ");
System.exit(0);
}
//Thread init_Thread = new Thread();
}
private static int initialize(Socket socket ) throws IOException{
System.out.println("hello");
int rt_value = 0 ;
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
System.out.println("server: " + br.readLine());
pw.println("192.343.34.321");
// BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
//String userInput = userInputBR.readLine();
//out.println(userInput);
socket.close();
return rt_value = 1 ;
}
public void run(){
}
}
server side program
public class server {
protected static String server_IP ;
public static void main(String[] args) throws IOException {
int server_Port = 5555 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
server_IP = iAddress.getHostAddress();
System.out.println("Server IP address : " +server_IP);
} catch (UnknownHostException e) {
}
ServerSocket serverSocket = new ServerSocket(server_Port);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
pw.println("Connection confirmed ");
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
pw.println("your ip address is " + str);
pw.close();
//socket.close();
//System.out.println("Just said hello to:" + str);
}
How do I connect to the server socket using the ip address and port number (client is running on a different machine than server).
When I change the server_IP in client to "local host", it works perfectly.
To connect in your code you use:
Socket socket = new Socket(server_IP,server_Port);
So you could use:
Socket socket = new Socket("192.168.1.4", 5555);
It looks like you have this in your code so I'm not sure what problem you're having.
Don't forget that you have to setup your router to forward ports if it is located outside of your local network.
http://www.wikihow.com/Set-Up-Port-Forwarding-on-a-Router
Don't forget that if you are running a firewall, this can also interfere with the connection.
Update /etc/hosts
Add following line
127.0.1.1 192.168.10.109
I write simple application to communication client - server.
Sending data from client to server works perfectly. Server calculates some stuff and tries to send to client result but it doesn't work.
here's code for client:
public static void main(String argv[])
{
try
{
View view = new View();
view.printStartMessage();
view.printManual();
String input;
String output;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
do
{
if (inFromServer.ready())
{
output = inFromServer.readLine();
view.print(output);
}
input = inFromUser.readLine();
outToServer.writeBytes(input + "\n");
}
while(!"EXIT".equals(input));
clientSocket.close();
}
catch (IOException ex)
{
Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
and here's for server:
public static void main(String argv[])
{
try
{
Protocol protocol = new Protocol();
View view = new View();
String clientData;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
while ((clientData = inFromClient.readLine()) != null)
{
view.print("Odebrano: " + clientData);
if("EXIT".equals(clientData))
{
break;
}
protocol.checkUsersInput(clientData);
if(protocol.isError())
{
outToClient.writeBytes(protocol.getError());
view.printError(protocol.getError());
break;
}
if (protocol.isResultReady())
{
outToClient.writeBytes(protocol.getResult());
view.print(protocol.getResult());
}
}
break;
}
}
catch (IOException ex)
{
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
I don't know even what generates problem, client or server.
Anyone have any idea?
Thanks from advice.
EDIT:
Ok, problem solved. Server didn't sent end line tag so readLine method just didn't know where line have ended.