For its partner app I switched the Client and Server code and the ports. Ran both these codes in two separate terminals. They were able to connect with each other but I was not able send message from one terminal to the other.
import java.net.*;
import java.io.*;
import java.util.Scanner;
class ChatHead1
{
public static void main()throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Client
Socket sock = new Socket("127.0.0.1", 2000);
OutputStream ostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);
System.out.print("\nYou:");
String message1 = br.readLine(); //Inputting Message For Sending
dos.writeBytes(message1);
//Server
ServerSocket sersock = new ServerSocket(5000);
System.out.print("\nThem: ");
Socket sockServ = sersock.accept();
InputStream istream = sockServ.getInputStream();
DataInputStream dstream = new DataInputStream(istream);
String message2 = dstream.readLine();
System.out.println(message2); //Printing Received Message
//Client Close
dos.close();
ostream.close();
sock.close();
//Server Close
dstream .close();
istream.close();
sockServ.close();
sersock.close();
}
}
I would suggest that you should only use one Server/Client, because its a two way connection.
I dont really see why you are using a Client and a Server.
Try dos.flush(); after dos.writeBytes(message1);
Related
I am trying to do a basic networking program using sockets
Server:
import java.io.*;
import java.net.*;
class Socketserver{
public static void main(String[]z)throws IOException{
System.out.println("Server is started");
ServerSocket ss=new ServerSocket(9999);
System.out.println("Waiting for client request");
Socket s=ss.accept();
System.out.println("client connected");
InputStreamReader a=new InputStreamReader(s.getInputStream());
BufferedReader b=new BufferedReader(a);
String str=b.readLine();
System.out.println("Client data"+str);
String nickname=str.substring(0,3);
OutputStreamWriter os=new OutputStreamWriter(s.getOutputStream());
PrintWriter out=new PrintWriter(os);
out.write(str);
os.flush();
System.out.println("data sent from server to client");
}}
Client
import java.io.*;
import java.net.*;
class Socketclient{
public static void main(String[]z)throws IOException{
String ip="localhost";// for same machine
int port=9999;
Socket s=new Socket(ip,port);
String str="Rujhaan";
OutputStreamWriter os=new OutputStreamWriter(s.getOutputStream());
PrintWriter out=new PrintWriter(os);
out.write(str);
os.flush();
InputStreamReader a=new InputStreamReader(s.getInputStream());
BufferedReader b=new BufferedReader(a);
String nickname=b.readLine();
System.out.println("data from server"+nickname);
}
}
The program compiles and there is no problem on the server but running client always gives connection refused or connection timed out exception.
I have tried different port names and also there is nor firewall problem.
Please suggest me what to do....
Problem is the function readLine. The Specification says the method read the stream until an new line ("\n") is received
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()
Change your input string to
String str="Rujhaan\n";
will works or alternative close the OutputStream on client to terminate data transmission.
out.close();
I am trying to make a java program for client-server communication
I need to initialize a server socket and a client socket.
The server socket will accept a connection from the client.
After the connection has been accepted, the input i give to the client will be submitted to the server which will tell the client if the communication was successfull or not.
This is my code :
import java.io.*;
import java.net.*;
public class ClientServer {
public static void main(Strings args[]) throws Exceptions{
/*initialize server socket*/
Socket client_socket = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
String serverMsg = null;
while ((serverMsg = reader.readLine()) != null) {
System.out.println("Client: " + serverMsg);
ServerSocket server_socket;
server_socket=new ServerSocket(12345);
while (true) {
Socket mysocket=server_socket.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
writer.write("prova\n");
System.out.printls("data sent");
}
}
}
but I need to get input from keyboard, not "from the code".
Thanks a lot.
I am planning to create master and slave bots using Java Sockets.
I am testing on to something and have successfully implemented the following client and server programs:
Server.java
import java.io.*;
import java.net.*;
class Server{
public static void main(String ... args){
try{
ServerSocket ss = new ServerSocket(1201);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msgin = "", msgout = "";
while(!msgin.equals("end")){
msgin = din.readUTF();
System.out.println(msgin);
msgout = br.readLine();
dout.writeUTF(msgout);
// dout.flush();
}
s.close();
}catch(Exception e){
}
}
}
Client.java
import java.io.*;
import java.net.*;
class Client{
public static void main(String ... args){
try{
Socket s = new Socket("10.0.0.49",1201);
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msgin = "", msgout = "";
while(!msgin.equals("end")){
msgout = br.readLine();
dout.writeUTF(msgout);
msgin = din.readUTF();
System.out.println(msgin);
}
}catch(Exception e){
}
}
}
The thing is that I want constant input from both server and the client.
Current Scenario:
Client sends and waits for server to respond.
Server sends and waits for the client to respond.
Desired Working:
Client can send as many messages, and not wait for the server and vice versa.
I've created a TCP Server in Java and a TCP client in Ruby. The problem is I'm not able to send more than 1 message in the same connection, Only the first message is sent while the other one is not sent.
here is the Java code
package com.roun512.tcpserver;
import java.io.*;
import java.net.*;
public class Program {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while(true)
{
Socket connection = Socket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
And here is the client code
Client.rb
require 'socket'
class Client
def initialize()
server = TCPSocket.open("127.0.0.1", 6789)
if server.nil?
puts "error"
else
puts "connected"
end
server.puts("Hello\r\n")
sleep 2
server.puts("There\r\n")
server.close
end
end
Client.new()
I'm only receiving Hello. I have tried many other ways but none worked.
So my question is how to send more than 1 message in a single connection, Any help would be appreciated :)
Thanks in advance!
Socket.accept() waits for new connection after reading the first line.
Try the following:
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket Socket = new ServerSocket(6789);
while (true)
{
Socket connection = Socket.accept();
while(true)
{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connection.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence + '\n';
outToClient.writeBytes(capitalizedSentence);
System.out.println("Sent msg");
}
}
}
If it works, change while (true) to some meaningful condition and don`t fotget to close the connection after the work is done.
I'm new to the network communication and I'm trying to build client-server application.
protected void init(){
Server myServer = new Server();
Client myClient = new Client();
}
That's my Client class:
public class Client {
public Client() {
init();
}
private void init() {
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
DataInputStream stdIn = new DataInputStream(System.in);
try {
echoSocket = new Socket("localhost", 1234);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
os.writeInt(stdIn.readInt());
echoSocket.getOutputStream().close();
echoSocket.getInputStream().close();
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And that's server:
public class Server {
public Server() {
init();
}
private void init() {
try {
boolean run = true;
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readInt());
s.getInputStream().close();
s.getOutputStream().close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
First of all:
Can I initialize client and server simply like i did? new Server() and new Client()?
Question 2:
Is it important what i initialize at first? client or server?
Question 3:
When i compile this code with client first initialized, i become Connection refused: connect. I know it means that there is no listening socket running on the port you are trying to connect to. That's why server must go first, i think. Is it so? can i fix it using setSoTimeout and how?
Question 4:
When i compile it with server and then client, output is nothing. And i think it has nothing to do with client, because if i try to print "1", for example, it doesn't work either. I think it just waits for the client and does nothing that goes after. How can i fix this? maybe setSoTimeout goes here too?
You can't have both client and server in the same thread.
As you already have observed, the server accepts the connection and tries to read something. It doesn't know that the client is running in the very same thread.
Either make a multi-threaded application, where client and server have their own thread. Or make two prgrams that run independently of each other. The latter would be also the "normal case".
Make two different projects, first run server than client.
Server will write on console "Server started" than run client it will ask your name, type your name press ok . Your name will be sent to server and server will reply saying hello to you.
Here is server code
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket ss= new ServerSocket(2224);
System.out.println("Serever started");
while(true)
{
Socket s=ss.accept();
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os);
String name=br.readLine();
String message="Hello "+name+"from server";
pw.println(message);
pw.flush();
}
}
catch(Exception exp)
{
System.out.println("Excepttion occured");
}
}
}
Here is client code
import java.net.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s=new Socket("localhost",2224);
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os,true);
String message = JOptionPane.showInputDialog("Give your name");
pw.println(message);
pw.flush();
String servermessage = br.readLine();
JOptionPane.showMessageDialog(null, servermessage);
s.close();
}
}