I wrote a simple socket tutorial about sending/receive messages between client and server. I used DataOutputStream to write the string in stream but server couldn't read it if I used BufferedReader
If I use PrintWriter to write(client side), it works.
What's wrong here? Tks so much.
1. Client:
client = new Socket("localhost", 1982);
DataOutputStream opStr = new DataOutputStream(client.getOutputStream());
//pw = new PrintWriter(client.getOutputStream(), true);
//pw.println("Hello, is there anybody out there?");// Can be read by BufferedReader
opStr.writeUTF("Hello, anyone there?");
opStr.flush();// BufferedReader can't read it
2. Server:
openServer();// port 1982
while(true) {
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
DataInputStream inStr = new DataInputStream(
clientSocket.getInputStream());
//System.out.println("M1: Got msg " + inStr.readUTF());// It showed the content
BufferedReader bfReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("got Messages: ");
String strLine = "";
// Don't show anything
while ((strLine = bfReader.readLine()) != null) {
System.out.println(strLine);
}
}
You can't. If you use writeUTF() at one end, you have to use readUTF() at the other end.
You just have to decide which API you're going to use, instead of trying to mix and match them.
You want to read the files as either text e.g. BufferedReader OR binary e.g. DataInputStream. So you can't use both.
Server.java
public class Server
{
public static void main(String[] args)
{
DataInputStream inStr = null;
String str;
openServer();// port 1982
while(true)
{
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
try
{
inStr = new DataInputStream(clientSocket.getInputStream());
str = inStr.readUTF();
System.out.print((String) str);
System.out.flush();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
catch (Throwable anything)
{
System.err.println("Exception caught !: " + anything);
}
finally
{
if (inStr != null)
{
try
{
inStr.close();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
}
}
}
}
}
Related
I am trying to send a json string from a client to a server. The code seems to send the string correctly from the client, but the server won't receive the code and print out the results. What am I doing wrong?
InputStream inp;
PrintStream ps = null;
while(true){
try{
ps = new PrintStream(socket.getOutputStream());
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
System.out.println("hello"); //This works
String input = brinp.readLine();
System.out.println(input); //Nothing is printed here
}
catch(IOException e){
System.out.println(e);
}
}
This is my server side code
//Socket s was initialized above
BufferedReader br;
DataOutputStream dos;
try {
dos = new DataOutputStream(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PatientStructure patient = new PatientStructure((int) (Math.random() * 10 + 1),
textFieldFirstName.getText(), textFieldLastName.getText(), new String[1]);
String sendString = gson.toJson(patient);
dos.writeBytes(sendString);
System.out.println("hello"); //This runs so my guess is that the above line has worked correctly
/**if (br.readLine().equals("ACCEPTED"))
dos.writeBytes(sendString + "/n");
else
System.out.println("Error");**/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Both programs are connected to the same socket and problem seems to be in these lines. Thanks in advance :)
I have a Server-Client program where I send a small messsage to the client using JLabel. When that message is recieved from server that particular client must send a response immediately. But it is not sending any message . Can somebody look at my code and tell me where my mistake is?
//SERVER
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
while (true) {
socket = listener.accept();
socketList.add(socket);
//socketList.add(listener.accept());
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
}
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
}
//CLIENT
void connect_server() throws IOException
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
while(true){
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
if(answer != null)
{
PrintStream pr = new PrintStream(s.getOutputStream());
InputStreamReader rd = new InputStreamReader(System.in);
BufferedReader ed = new BufferedReader(rd);
String temp = ed.readLine();
pr.println(temp);
JOptionPane.showMessageDialog(null,"Answer is not null"); //THIS WORKS
}
}
}
catch (ConnectException e) {
JOptionPane.showMessageDialog(null, e);
}
catch (SocketException e) {
JOptionPane.showMessageDialog(null, e);
}
}
Some points that you missed in your implementation:
the streams and sockets are never closed
in the client i do not see the point of the endless loop
the client should initialize the communication by sending a message via output stream (not to try to read first)
For a simple example the steps should be:
Start sever to listen and once a connection is established to read the message (you did)
The client should sent a message via output stream and close the steams and the socket
The severs should close the streams and the sockect for the established connection
Example:
//Server
socket = listener.accept();
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream());
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
String msg = "Message received";
pr.write(msg,0,msg.length());
pr.newLine();
ed.close();
pr.close();
socket.close();
//Client
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(s.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sendMessage = "Send Message";
pr.write(msg,0,msg.length());
pr.newLine();
String answer = input.readLine();
System.out.println(answer);
JOptionPane.showMessageDialog(null,"Answer is not null");
input.close();
pr.close();
s.close();
UPDATE
reading from input stream continuously:
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line=input.readLine())!=null){
//do something with line
}
I will suggest a simple approach where server is sending the hi msg to client.
For server:
//Server
ServerSocket ss=new ServerSocket(3554);
socket = ss.accept();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getOutputStream()));
String msg ="Hi from server"
bw.write(msg);
String msgFromClient=br.readLine();
System.out.println(msgFromClient);
bw.close();
socket.close();
For Client:
//Client
Socket socket=new Socket("localhost",3554)
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String received = input.readLine();
System.out.println(received);
bw.write("Client recieve :"+received);
br.close();
bw.close();
socket.close();
I'm connecting to a remote TCP Listener that receives a string, and responds with a response.
Going from my Windows 8 Phone App, to a Java Jar. The Jar IS receiving the message, but the Windows 8 Phone App is not getting the response.
C# Code
outputClient.Connect (/IP ADDRESS/, /Port/);
using (Socket sock = outputClient.Client) {
sock.Send (UTF8Encoding.ASCII.GetBytes (broadcastMessage));
var response = new byte[100];
sock.Receive (response);
var str = Encoding.ASCII.GetString (response).Replace ("\0", "");
Console.WriteLine ("[RECV] {0}", str);
} <-- JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED
Java Code
String clientSentence;
ServerSocket socketServer = new ServerSocket(/* PORT */);
while (true)
{
Socket connectionSocket = socketServer.accept();
connectionSocket.setKeepAlive(true);
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
if (clientSentence != null)
{
try
{
JsonObject json = new JsonParser().parse(clientSentence).getAsJsonObject();
String un = json.get("Username").toString();
String uuid = "2c9c79a096ef4d869fb1d1e07469bb41".replaceAll(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
"$1-$2-$3-$4-$5");
var val = /* Get val */
String response = gson.toJson(val);
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
outToClient.write(response);
outToClient.newLine();
outToClient.flush();
}
}
connectionSocket.close();
}
A little more explanation: JAVA CODE DOESN'T GET HIT UNTIL THIS LINE IS COMPLETED means that the socket appears to not be sending until using (Socket sock = outputClient.Client) is no longer being used.
I fixed it by replacing the C# code with:
using (TcpClient client = new TcpClient (/IP ADDRESS/, /PORT/))
using (NetworkStream stream = client.GetStream ())
using (StreamReader reader = new StreamReader (stream))
using (StreamWriter writer = new StreamWriter (stream)) {
writer.AutoFlush = true;
foreach (string lineToSend in linesToSend) {
Console.WriteLine ("Sending to server: {0}", lineToSend);
writer.WriteLine (lineToSend);
string lineWeRead = reader.ReadLine ();
Console.WriteLine ("Received from server: {0}", lineWeRead);
Thread.Sleep (2000); // just for effect
}
Console.WriteLine ("Client is disconnecting from server");
}
i have this assignment where i am supposed to write a proxy server that uses java sockets to handle get requests from a client. I am now stuck and have been looking all over google to find the answer but without success.
Christoffers solution helped my with my first problem. Now that i have updated the code this is what i am using.
The problem is that it only downloads parts of most webpages before it gets stuck on sending the packets back to the client loop. At the moment I cant explain why it is behaving the way it is.
public class MyProxyServer {
//Set the portnumber to open socket on
public static final int portNumber = 5555;
public static void main(String[] args){
//create and start the proxy
MyProxyServer myProxyServer = new MyProxyServer();
myProxyServer.start();
}
public void start(){
System.out.println("Starting MyProxyServer ...");
try {
//create the socket
ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber);
while(true)
{
//wait for a client to connect
Socket clientSocket = serverSocket.accept();
//create a reader to read the instream
BufferedReader inreader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "ISO-8859-1"));
//string builder for preformance when we loop over the inputstream and read lines
StringBuilder builder = new StringBuilder();
String host = "";
for (String buffer; (buffer = inreader.readLine()) != null;) {
if (buffer.isEmpty()) break;
builder.append(buffer.replaceAll("keep-alive", "close"));
if(buffer.contains("Host"))
{
//parse the host
host = buffer.replaceAll("Host: ", "");
}
System.out.println(buffer);
}
String req = builder.toString();
System.out.println("finshed reading \n" + req);
System.out.println("host: " + host);
//new socket to send the information over
Socket s = new Socket(InetAddress.getByName(host), 80);
//printwriter to send text over the output stream
PrintWriter pw = new PrintWriter(s.getOutputStream());
//send the request from the client
pw.println(req+"\r\n");
pw.flush();
//create inputstream to receive the web page from the host
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
//create outputstream to send the web page to the client
BufferedOutputStream outbuffer = new BufferedOutputStream(clientSocket.getOutputStream());
byte[] bytebuffer = new byte[1024];
int bytesread;
//send the response back to the client
while((bytesread = in.read(bytebuffer)) != -1) {
System.out.println(bytesread);
outbuffer.write(bytebuffer,0, bytesread);
outbuffer.flush();
}
System.out.println("done sending");
//close the streams
inreader.close();
s.close();
pw.close();
outbuffer.close();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch(RuntimeException e){
e.printStackTrace();
}
}
}
If anyone could explain to me why i cant get it working correctly and how to solve it I would be very grateful!
Thanks in advance.
I've just begun socket programming, and I'm working on an Echo server in Java. One of the things I'd like to do is implement the server in both TCP and UDP and allow the client to choose which protocol to use at runtime.
This is a noob question, but how do I allow a user this option to choose TCP or UDP protocols? I tried putting in an if-else at the beginning which branched on the protocol choice from scanner input, but that just skips the both blocks irrespective of the choice?
Thanks.
I've implemented the TCP echo server:
public class EchoServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10007);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10007.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String cAddress = "";
String inputLine;
cAddress = clientSocket.getInetAddress().toString();
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine + " " + cAddress + " ");
out.println(inputLine + " " + cAddress);
if (inputLine.equals("bye"))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
And the client side:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class EchoClient {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String serverHostname;
System.out.println("Enter an IP value: ");
serverHostname = s.next();
//String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 10007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
There is no way (that I know of) to do conditionals in Java without using the If statement. If your else-if wasn't working, then you were checking the condition wrong. To compare strings in java you use String.equals( String ), you can't use ==.
Try using it again on standard input, but just do something simple.
Like:
Scanner scan = new Scanner( System.in );
System.out.println( "use tcp?" );
String in = scan.nextLine();
if( in.indexOf( "y" ) >= 0 || in.indexOf( "Y" ) >= 0 ){
System.out.println("using tcp");
}else{
System.out.println("not using tcp, use udp instead?");
}
If you want to know how it is possible in the socket level, you should be able to bind your TCP serversocket and UDP serversocket in to the same port. You will have to have separate threads handling each of the sockets. For instructions how to write UDP server socket (called DatagramSocket check this tutorial.
You need to open two separate sockets with different ports in your application.
In addition to that, you need separate Threads in Java, which usage is described in a lot of how to's and tutorials.
For Socket creation use DatagramSocket for UDP and ServerSocket for TCP. I don't know, what you want to do, but you have to know that you have to handle dataloss in UDP for yourself. UDP is common used in streaming audio or video, where it is uncritical, to loss some data.
Validate your application needs. For further information see http://en.wikipedia.org/wiki/User_Datagram_Protocol#Comparison_of_UDP_and_TCP.
Your welcome.