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();
}
}
Related
the first is my client, and second is server side.why the client can't send its second round msg to the server through socket? when you put something in the console, the server will respond through socket, and then send back the msg to client.but when i put something in the console for the second time, the msg cannot be sent to server anymore, please tell me why. thanks
package client;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
static Socket sock ;
static InputStreamReader IR;
public static void main(String[] args) throws IOException,
InterruptedException
{
Client client = new Client();
sock = new Socket("localhost", 1112);
IR = new InputStreamReader(sock.getInputStream());
client.run();
}
public void run() throws IOException, InterruptedException
{
while(true)
{
PrintStream PS = new PrintStream(sock.getOutputStream());
Scanner sc = new Scanner(System.in);
System.out.println("Enter your ageļ¼");
int age = sc.nextInt();
PS.println(age);
if(age == 0)
{
break;
}
System.out.println("here");
BufferedReader BR = new BufferedReader(IR);
String MSG = BR.readLine();
System.out.println("client: server has received "+MSG);
Thread.sleep(1000);
}
sock.close();
}
}
package server;
import java.io.*;
import java.net.*;
public class Server {
static ServerSocket serverSocket;
public static void main(String[] args) throws IOException,
InterruptedException {
Server server = new Server();
serverSocket = new ServerSocket(1112);
server.run();
}
public void run() throws IOException, InterruptedException
{
while(true)
{
//ServerSocket serverSocket = new ServerSocket(1112);
Socket socket = serverSocket.accept();
InputStreamReader IR = new
InputStreamReader(socket.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String msg = BR.readLine();
System.out.println("server: I have received "+msg);
Thread.sleep(2000);
if(msg != null)
{
PrintStream PS = new
PrintStream(socket.getOutputStream());
PS.println(msg);
}else
{
break;
}
}
serverSocket.close();
}
}
So when a client socket attempts to connect to a server socket, it gets put on a queue on the server-side. Then, the .accept() method on the server socket takes that request off the queue and "connects" the two sockets.
So, in your code,
the client requests connection,
the server accepts it,
client sends age to server,
server reads it and sends it back,
client sends another age to the server
server never does anything
The problem occurs after step 4 on the server-side. It calls the .accept() method again, but there is no client requesting connection so that .accept() just waits until it gets a socket requesting connection (it's called a blocking method).
You could fix this problem by moving the Socket socket = serverSocket.accept() out of the while(true) loop on the server
This code is about client and server communication in java. I can run both codes in my PC and can connect client and server. But how will I connect 2 computers as a client and server. Here are my codes for server and client as follows:
MyServer1
//code for server
import java.io.*;
import java.net.*;
public class MyServer1
{
ServerSocket ss;
Socket s;
DataInputStream dis;
DataOutputStream dos;
public MyServer1()
{
try
{
System.out.println("Server Started");
ss=new ServerSocket(10);
s=ss.accept();
System.out.println(s);
System.out.println("CLIENT CONNECTED");
dis= new DataInputStream(s.getInputStream());
dos= new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main (String as[])
{
new MyServer1();
}
public void ServerChat() throws IOException
{
String str, s1;
do
{
str=dis.readUTF();
System.out.println("Client Message:"+str);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s1=br.readLine();
dos.writeUTF(s1);
dos.flush();
}
while(!s1.equals("bye"));
}
}
MyClient1
//code for client
import java.io.*;
import java.net.*;
public class MyClient1
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient1()
{
try
{
//s=new Socket("10.10.0.3,10");
s=new Socket("localhost",10);
System.out.println(s);
din= new DataInputStream(s.getInputStream());
dout= new DataOutputStream(s.getOutputStream());
ClientChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ClientChat() throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String s1;
do
{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message:"+din.readUTF());
}
while(!s1.equals("stop"));
}
public static void main(String as[])
{
new MyClient1();
}
}
Client Just needs the IP of the Server.You have to find out the IP of the server and tell the client about it, like:
String serverName = "IP of server comes here"; // Indicating the place to put Server's IP
s = new Socket(serverName, 10);
Server needs no change.
You have to just enter ip of the server while creating Socket Instance.
i suggest you to follow steps
1) start hotspot in any one computer which you going to use as server
2) in second computer start wifi and connect with hotspot which we just started.
3) now ho to sharing center and click on network you connect and check detail and copy dns server ip and paste it in client program
I've been trying to fix "connection reset" problem in a simple java server-client program for a while.
My scenario is like this
client program will take filename as input, then send it to server program. Server will check if that file exists in the directory. If exist then server will print "ok", otherwise "file not found"
I'm getting this execption java.net.SocketException: Connection reset
Server program
package tcpserver;
import java.net.*;
import java.io.*;
public class TCPServer {
ServerSocket serversocket;
Socket socket;
BufferedReader buffread, buffout;
String filename;
String strDir = "D:\";
private void findFile(String name) {
File fileObj = new File(strDir);
File[] fileList = fileObj.listFiles();
if (fileList != null) {
for (File indexFile : fileList) {
if (name.equalsIgnoreCase(indexFile.getName())) {
System.out.println("200 ok ");
} else {
System.out.println("File Not found");
}
}
}
}
public TCPServer() {
try {
//creating server object
serversocket = new ServerSocket(6666);
socket = serversocket.accept();
//get input stream through the socket object from buffer
buffread = new BufferedReader(new InputStreamReader(socket.getInputStream()));
filename = buffread.readLine();
findFile(filename);
} catch (IOException ex) {
//System.err.println(ex);
ex.printStackTrace();
}
}
public static void main(String[] args) {
TCPServer serverObject = new TCPServer();
}
}
Client program
package tcpclient;
import java.net.*;
import java.io.*;
public class TCPClient {
BufferedReader bffread, bffinput;
String fileInput;
public TCPClient() {
try {
//Creating socket
Socket socket = new Socket("localhost", 6666);
System.out.println("Enter filename");
bffinput = new BufferedReader(new InputStreamReader(System.in));
OutputStream outputObject = socket.getOutputStream();
} catch (Exception ex) {
System.out.println("Unhandled exception caught");
}
}
public static void main(String[] args) {
TCPClient clientObject = new TCPClient();
}
}
Exception stack
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at tcpserver.TCPServer.<init>(TCPServer.java:38)
at tcpserver.TCPServer.main(TCPServer.java:47)*
Any help/suggestion is appreciated. Thanks in advance
Your server accepts the connection, but never sends anything back. The "200 OK" message gets written to stdout, not to the socket. Then the server terminates, closing the connection. At that time the client, still waiting for data, gets the exception.
I guess you want to send "200 OK" the client. So you have to pass the socket, or at least the OutputStream of the socket to findFile(), and write the response into that.
Alternatively, and a bit cleaner: return the response string from findFile(), and send it in the calling method, so findFile() doesn't even need to know about sending the response.
You should also close the socket in the block where you open it, so that data that might still be in a buffer in memory will be sent.
Client
Your client programme is not reading anything from console and sending it over to socket.
Change it to something like this..
public TCPClient() {
try {
//Creating socket
Socket socket = new Socket("localhost", 6666);
System.out.println("Enter filename");
bffinput = new BufferedReader(new InputStreamReader(System.in));
String filename = bffinput.readLine();
OutputStream outputObject = socket.getOutputStream();
// send filename over socket output stream
outputObject.write(value.getBytes());
} catch (Exception ex) {
System.out.println("Unhandled exception caught");
}
}
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.
I wrote a server-client communication program and it worked well.
Client module
import java.io.*;
import java.net.*;
class Client {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
while(true){
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("myname.domain.com", 2343);
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Ready");
sentence = in.readLine();
out.writeBytes(sentence + '\n');
modifiedSentence = in.readLine();
System.out.println(modifiedSentence);
}
clientSocket.close();
}
}
Server module
import java.net.*;
public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
String cap_Sentence;
ServerSocket my_Socket = new ServerSocket(2343);
while(true) {
Socket connectionSocket = my_Socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = in.readLine();
cap_Sentence = "Raceived:" + clientSentence + '\n';
out.writeBytes(cap_Sentence);
}
}
}
The above is the code for a single client - server communication, now I want multiple client to interact with that server. I googled for it and found that it can be done with the use of a thread for each single client to talk to the server, but since I am a beginner I don't know exactly how to implement. So somebody please tell me how to do or give me some idea about it.
MainServer class
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(2343);
} catch (IOException e) {
System.err.println("Could not listen on port: 2343");
}
while(listeningSocket){
Socket clientSocket = serverSocket.accept();
MiniServer mini = new MiniServer(clientSocket);
mini.start();
}
serverSocket.close();
}
}
Helper Class
public class MiniServer extends Thread{
private Socket socket = null;
public MiniServer(Socket socket) {
super("MiniServer");
this.socket = socket;
}
public void run(){
//Read input and process here
}
//implement your methods here
}
You want to look into Java concurrency. That's the concept of one Java program doing multiple things at once. At a high level you will be taking your while(true) { //... } block and running it as part of the run() method of a class implementing Runnable. You'll create instances of Thread that invoke that run() method, probably one per client you expect.
For a really good, deep understanding of all that Java offers when it comes to concurrency, check out Java Concurrency in Practice.
Well, when I do something like that, I implement a listener that manages the server side, so when a client (the client won't probably need changes) connects, the server launch one thread to work with that client.
while (!stop)
{
socket = serverSocket.accept();
HiloSocket hiloSocket = new HiloSocket(socket, this);
hiloSocket.start();
}
Of course, HiloSocket extends Thread and it has the logic behind to manage the client...