I am quite a newbie to Java. Please excuse me if you find this as a very basic question.There are many answers available already in stack overflow about this and I went through almost all the possible helps i can get in Stack overflow and also in some other forums. Unfortunately none of them helped me.
I have client/server program in which the client send a string to server and server just attaches another string to the string sent by client and sends it back to the client.
Server program looks like this.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) {
try
{
ServerSocket server = new ServerSocket(7300);
Socket s = server.accept();
DataInputStream inp = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
String str =inp.readUTF();
str = str+" buddy!";
out.writeUTF(str);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client looks like This.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.*;
public class client {
public static void main(String[] args) {
try
{
Socket s = new Socket("192.168.1.3",7300);
DataInputStream inp = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeUTF("hi");
System.out.println(inp.readUTF());
Thread.sleep(2000);
out.writeUTF("hello");
System.out.println(inp.readUTF());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Everything works fine while client writes "hi" and when client starts sending "hello" i am getting Connection reset error. I am not getting what mistake am i doing please help me in resolving this.
The output with the error i am getting looks like this.
hi buddy!
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.DataOutputStream.write(Unknown Source)
at java.io.DataOutputStream.writeUTF(Unknown Source)
at java.io.DataOutputStream.writeUTF(Unknown Source)
at sokry.client.main(client.java:18)
In your server example, readUTF is only called once on the DataInputStream, even though the client wrote to the DataOutputStream twice. Thus, simply adding
str = inp.readUTF();
str = str + " buddy!";
out.writeUTF(str);
to your server example, after the last out.writeUTF(str), will solve your problem.
do comment on following line of your client.java file and try.it will work
Thread.sleep(2000);
`//out.writeUTF("hello");;
//System.out.println(inp.readUTF());
because when you are sending "hi" from client to server and server gives reply then it finished it work and it stop connection but in client.java you sending another request to server but server is at rest.
you should start server until client finish it work..
hope it will wait
Related
i want to know the functionality of sockets in java. when i am creating some http-server i can use some ready to use sockets for secure and non-secure communication between two parties. but i never installed tomcat to my project, so my question is: how can java create a tcp / ip connection without a web-server? Can someone post me some link to clear this question?
In my case i used this to create a SSLSocket:
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass {
public static void main(String args[]) throws Exception {
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
ServerSocket ss = ssf.createServerSocket(5432);
while (true) {
Socket s = ss.accept();
PrintStream out = new PrintStream(s.getOutputStream());
out.println("Hi");
out.close();
s.close();
}
}
}
Thank u a lot,
Mira
I'm trying to make a program that get data from here but an error appear (403 error)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Test {
public static void main(String[] args) throws IOException {
URL urlObject;
String codigo;
try{
urlObject=new URL("http://www.pccomponentes.com/intel_core_i5_6600_3_3ghz_box.html");
InputStreamReader isr = new InputStreamReader(urlObject.openStream());
BufferedReader br=new BufferedReader(isr);
while((codigo=br.readLine())!=null)
System.out.println(codigo);
br.close();
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
When I run the program this error appear:
java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.pccomponentes.com/intel_core_i5_6600_3_3ghz_box.html
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at Test.Test.main(Test.java:17)
The purpose of the program it's get the price of the product and print it with a System.out.println, how can I do that?
I have just tested with curl it works, but if I set the User-Agent used by Java by default I get this 403 HTTP error. It seems that the web master of this website doesn't like Java :-)
To work around this, simply set another User-Agent by doing this:
urlObject=new URL("http://www.pccomponentes.com/intel_core_i5_6600_3_3ghz_box.html");
URLConnection c = urlObject.openConnection();
c.setRequestProperty("User-Agent", "<put a the user agent of your choice here>");
InputStreamReader isr = new InputStreamReader(c.getInputStream());
If you don't know which User-Agent to use, use the one of your browser that you can get from here
As I mentioned in this question, I was getting a SocketException: Connection reset.
After implemented Aaron's answer it seems to be working as intended. But today that I run the code again, I got once again the connection reset error.
The problem is that if I run my code like 5 times, it seems to work 2/5 times and the rest gives me the error...
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket server = new ServerSocket(444);
while (true) {
Socket socket = server.accept();
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
Object objRead = objIn.readObject();
if (objRead != null) {
System.out.println(objRead);
}
}
}
}
Client:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap;
public class Client {
public static void main(String[] args) throws IOException {
Socket sock;
int port = 444;
HashMap<Integer, String> mapSend= new HashMap<>();
mapSend.put(1,"row1");
mapSend.put(2,"row2");
sock = new Socket(InetAddress.getLocalHost(), port);
ObjectOutputStream objOut = new ObjectOutputStream(sock.getOutputStream());
objOut.writeObject(mapSend);
objOut.flush();
}
}
This is the error: (it appears on the output of the server, after I run the client):
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2308)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2716)
at java.io.ObjectInputStream$BlockDataInputStream.readFully(ObjectInputStream.java:2740)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1978)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1913)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at java.util.HashMap.readObject(HashMap.java:1154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at iotest.Server.main(Server.java:16)
On the client side I get no errors.
EDIT
Any way I can debug the client-server? That might help out to give you guys more info on this.
Close the output stream, instead of just flushing it.
NB readObject() doesn't return null unless you write null. The test is pointless.
I was wondering if i could get help making or finding a program that has the ability to send keyboard presses and receive them on another computer. I want to use this to play multiplayer flash-player games with friends across computers. I know there are some programs out there like "logmein" but both users cannot use the keyboard at the same time. (When i press a key the computer user cannot press a key at the same time because it wont respond.) I only know java and I am quite novice at it. Im guessing if i need to write it ill have to send the information through a port or onto a web-server. I would like to know your opinions and suggestions for this program, thanks guys.
Basically what you are looking for is a chatroom program? Have you tried looking into mIRC?
mIRC is a free internet relay chat. What exactly are the requirements for the program? Is there a certain size that it must be? Are these flash games that you and your friends are playing taking up your full computer screen?
Building a program would require a web-server(any computer with internet access would do), and you would have to open the ports on your network to allow the traffic to go through.
A basic server in java would look something like this:
Please note that after the first connection this "server" will close the connection.
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Server
{
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static BufferedReader bufferedReader;
private static String inputLine;
public static void main(String[] args)
{
// Wait for client to connect on 63400
try
{
serverSocket = new ServerSocket(63400);
while(true){
clientSocket = serverSocket.accept();
// Create a reader
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Get the client message
while((inputLine = bufferedReader.readLine()) != null)
{System.out.println(inputLine);}
serverSocket.close();
System.out.println("close");
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
And a client would almost be the same:
import java.net.Socket;
import java.io.PrintWriter;
public class client
{
private static Socket socket;
private static PrintWriter printWriter;
public static void main(String[] args)
{
try
{
//change "localhost" to the ip address that the client is on, and this number to the port
socket = new Socket("localhost",63400);
printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("Hello Socket");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
If I am not mistaken printWriter is a 16-bit operation, and in order to reduce lag, if you were just sending text then you might want to use printStream(). I believe that this might be a bit quicker.
I'm trying to make a simple HTML server that will read a request from my browser, parse the requested file from the request, then serve the appropriate HTML back to the browser. I need to be able to handle multiple requests, so I currently have a Server class acting as a parent of another runnable class RequestHandler. Each time a connection is made on the server, a new instance of the runnable class RequestHandler is run.
package server;
import java.io.IOException;
import java.net.ServerSocket;
public class Server {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(8000);
for(;;){
Object block = new Object();
RequestHandler handler = new RequestHandler(block, serverSocket);
handler.start();
try{
synchronized(block){
System.out.println("Server thread paused...");
block.wait();
System.out.println("Server thread creating new RequestHandler...");
}
}catch(InterruptedException e){
System.out.println("Can't be interrupted!");
e.printStackTrace();
}
}
}catch(IOException e){
System.out.println("IOException!");
e.printStackTrace();
}
}
}
package server;
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 RequestHandler extends Thread {
Object block;
ServerSocket serverSocket;
BufferedReader socketReader;
PrintWriter socketWriter;
public RequestHandler(Object block, ServerSocket serverSocket){
this.block = block;
this.serverSocket = serverSocket;
}
#Override
public void run() {
try{
System.out.println("Waiting for request...");
Socket clientSocket = serverSocket.accept();
System.out.println("Connection made.");
synchronized(block){
System.out.print("Notifying server thread...");
block.notify();
System.out.println("...done");
}
socketReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
socketWriter = new PrintWriter(clientSocket.getOutputStream(), true);
String input;
while((input = socketReader.readLine()) != null){
System.out.println(input);
}
}catch(IOException e){
System.out.println("IOException!");
e.printStackTrace();
}
}
}
The problem I'm running into is that I'm not sure how to combine all the lines of the request so that I can parse the requested file. If it's just constantly waiting on request input, I'll never get to a point where I can parse the entirety of the request. How can I solve this problem?
your while loop will only break once the connection between the client and the server is closed. Since the client is waiting on the same connection for a response after sending the request the connection will remain open, so your readline() will block. In your while loop you have to check after every line whether you have reached the end of the request data. For GET requests, you have to look for a blank line following HTTP headers. For POST requests, you have to parse incoming headers looking for <Content-Length: N>. THen process the remaining headers looking for the blank line (just like in the GET case). Once you find the blank like, you have to read <N> bytes. At this point you know you've finished processing request data and should break out of the read loop.
Read the HTTP spec for details.
The first line gives you the request method as well as the requested path, the following lines are the request headers, the header block ends with a blank line.
That said, you are reinventing the wheel: you could use com.sun.net.httpserver.HttpServer