Why cant I write to a socket's input stream java - java

So I Have two Similar classes to test Sockets that are the same from the lines down.
public class Server {
public static void main(String args[]) throws IOException, InterruptedException {
ServerSocket socket =new ServerSocket(80);
Socket client = socket.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//-----------------------------------------------------------------------------------
Scanner s = new Scanner(in);
InputStream txt = System.in;
Scanner text = new Scanner(txt);
while (true) {
if (text.hasNext()) {
out.write((text.next()+"\n").getBytes());
out.flush();
System.out.println("Sent");
}
if (s.hasNext()) {
System.out.println(s.next());
System.out.println("Received");
}
}
}
}
public class Client {
public static void main(String args[]) throws IOException, InterruptedException {
Socket socket =new Socket("localhost",80);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
//-----------------------------------------------------------------------------------
Scanner s = new Scanner(in);
InputStream txt = System.in;
Scanner text = new Scanner(txt);
while (true) {
if (text.hasNext()) {
out.write((text.next()+"\n").getBytes());
out.flush();
System.out.println("Sent");
}
if (s.hasNext()) {
System.out.println(s.next());
System.out.println("Received");
}
}
}
}
The goal is two way messaging.
When I type in either shell it says sent, however no text shows on the other shell.
Why are they not sending or receiving any text?
Any help is greatly appreciated.

Related

OutputStreamWriter and InputStreamReader for a Socket in Java, What am I doing wrong?

Using Sockets in java,
public class Server {
private static ServerSocket server;
private static int port = 9876;
static Socket p1 = null;
static Socket p2 = null;
public static void main(String args[]) throws IOException, ClassNotFoundException{
server = new ServerSocket(port);
Thread p1t = new Thread(new Runnable() {
#Override
public void run() {
try {
System.out.println("[Server] Waiting for connection");
p1 = server.accept();
System.out.println("[Server] Client connected");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p1.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String msg = String.valueOf(in.readLine());
System.out.println(msg);
out.write(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
});
p1t.start();
}
}
and
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
Socket socket = new Socket(InetAddress.getLocalHost().getHostName(), 9876);
if(socket.isConnected()) {
System.out.println("[Client] Connected");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new Thread(new Runnable() {
#Override
public void run() {
while(true) {
try {
System.out.println(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
while(true) {
Scanner s = new Scanner(System.in);
out.write(s.nextLine());
}
}
}
}
The client is supposed to send a message to the server, and the server is supposed to relay that message back to the client; but either the BufferedReader for Client and Server are not reading anything that is sent, or the BufferedWriter for Client and Server is not sending anything.
I've also tried manually sending text using out.write("test"); in both classes.
What am I doing wrong in this situation?

Send String from server to client - save it as textfile

I know how to send a file from a server to a client but how do I send a textstring to the client where the client save the string as a file? Should I use PrintWriter for this issue?
This is the code for sending a file from server to client:
Sending files through sockets
What I want to do is to (instead of sending a file), sending a String from the server and let the client receive it and save it as a file.
public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("send.jpg");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}
static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("recv.jpg");
copy(in, out);
out.close();
in.close();
}
static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
client();
}
}
in that case use ObjectOutputStream at server side to write String and use ObjectInputStream at client side to read String coming from server..
so your server() method will look like this..
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
OutputStream out = socket.getOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject("your string here");
oout.close();
}
and client() method will look like this..
static void client() throws IOException, ClassNotFoundException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
ObjectInputStream oin = new ObjectInputStream(in);
String stringFromServer = (String) oin.readObject();
FileWriter writer = new FileWriter("received.txt");
writer.write(stringFromServer);
in.close();
writer.close();
}
also throw ClassNotFoundException in main method.
public static void main(String[] args) throws IOException, ClassNotFoundException {.......}
done...

java: closing client socket resets server socket

I have a very simple capitalization Java program. Client sends text read from standard input to server which converts that text into capital letters. Program works well but once client is stopped (NetBeans ide used), server is also reset. Server socket should keep listening for new connection from clients regardless of a client being stopped.
public class Client
{
public static void main(String[] args) throws IOException
{
try(Socket s=new Socket("localhost",9090))
{
while(true)
{
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
BufferedReader rd=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader from=new BufferedReader(new InputStreamReader(System.in));
String read=from.readLine();
out.println(read);
String answer;
answer=rd.readLine();
System.out.println(answer);
}
}
}
}
public class Server
{
public static void main(String[] args) throws IOException
{
try(ServerSocket listener = new ServerSocket(9090);
Socket socket = listener.accept();)
{
while (true)
{
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Started...");
String transform=br.readLine();
String newStr=transform.toUpperCase();
out.println(newStr);
}
}
}
}
What happens is a normal behaviour. You server code only includes handling of a single client. The listener.accept() function only accepts latest connection to server. You need to put the listened.accept() in loop and handle all the exceptions that are raised within. The server-side code should look like this:
public class Server
{
public static void main(String[] args) throws IOException
{
try(ServerSocket listener = new ServerSocket(9090);
while (true) {
try {
Socket socket = listener.accept();)
…
} catch (SocketException ex) {
...
}
}
}
}
But keep in mind that this code will only handle single client at a time. No multi-threading in this code.
Your Server is closing the connection and then finishing becuase it is created outside the while loop. I believe this is what you need.
public class Server {
public static void main (final String[] args)
throws IOException {
while (true) {
try (ServerSocket listener = new ServerSocket(9090); Socket socket = listener.accept();) {
while (true) {
final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Started...");
final String transform = br.readLine();
if (transform == null)
break;
final String newStr = transform.toUpperCase();
out.println(newStr);
}
}
}
}
}

Sending Strings through Sockets

Here is the Server
public class SocketMsg {
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket("number goes here");
System.out.println("Server Ready");
ss.accept();
}
}
Client:
public class SocketMesg {
public static void main(String[] args) throws IOException{
Socket socket = null;
OutputStreamWriter osw;
String str = "Hello World";
try {
socket = new Socket("localhost", "number goes here");
osw =new OutputStreamWriter(socket.getOutputStream());
osw.write(str, 0, str.length());
} catch (IOException e) {
System.err.print(e);
}
finally {
socket.close();
}
}
Personally, the code works but the strings are not sending to the other host, I gave them the same number, but it is not working. The client is sending it back to the server on the DOS window. Did I make a error? What did I do wrong?
Your server-side at least needs the following.
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// process inputLine;
}
You need to flush outputstream to commit write buffer to the socket. Also be careful with charset if writing strings. This example explicitly uses UTF-8 through "low level" byte array buffer. I think you are practicing your first socket programming so I kept this very simple.
Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(1122);
System.out.println("Server Ready");
while(true) {
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
// client must send 1-10 bytes, no more in single command
byte[] buf = new byte[10];
int read = is.read(buf, 0, buf.length);
String cmd = new String(buf, 0, read, "UTF-8");
System.out.println(cmd);
socket.close(); // we are done, this example reads input and then closes socket
}
}
}
Client.java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = null;
// send max of 10 bytes to simplify this example
String str = "ABCDEFGHIJ";
try {
socket = new Socket("localhost", 1122);
OutputStream os = socket.getOutputStream();
byte[] buf = str.getBytes("UTF-8");
os.write(buf, 0, buf.length);
os.flush();
} catch (IOException ex) {
System.err.print(ex);
} finally {
socket.close();
}
}
}

Java Server And Client Socket Need Fix

Hello, I am new to java socket programming and I was just looking to see if somebody could give me some help.
I will post the code for the client and server then i will explain my problem...
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
while(running)
{
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
stream = new PrintStream(socket.getOutputStream());
stream.println("return: " + line);
}
}
}catch(IOException e)
{
System.out.println("Socket in use or not available: " + port);
}
}
public static void main()
{
run();
}
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintStream stream;
public static BufferedReader reader;
public static void main(String args[])
{
try
{
socket = new socket(ip, port);
stream = new PrintStream(socket.getOutputStream());
stream.println("test0");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
stream.println("test1");
line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
}catch(IOException e)
{
System.out.println("could not connect to server!");
}
}
So my problem is even if I get rid of the loop and try to make it send the string twice it won't send it. It will only do it once unless I close and make a new socket on the client side. So if anybody could give me an explanation to what I am doing wrong that would be great, and thank you so much.
Why are you openning your outstream inside your loop?
stream = new PrintStream(socket.getOutputStream());
Take this statement outside the loop and write to your stream inside your loop.
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket:
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");
Make sure you flush the output from your server:
stream.flush();
Thanks a lot to everybody who answered but i figures out what it was all along.
i read through some of the Oracle socket stuff and figured out that the server was supposed to be the first to send a message than the client receive and send and receive... so on and so forth so i will post my new code here in hopes somebody else trying to figure out the same thing can find it with ease
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintWriter print;
public static BufferedReader reader;
public Client(String ip, int port)
{
this.ip = ip;
this.port = port;
//initiate all of objects
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 5000);
print = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//start connection with server
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
//quick method to send message
public void sendMessage(String text)
{
print.println(text);
print.flush();
try
{
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
client.sendMessage("test");
client.sendMessage("test2");
client.sendMessage("test3")
}
//Server
public static int port = 9884;
public static boolean running = true;
public static ServerSocket serverSocket;
public static Socket socket;
public static PrintWriter writer;
public static BufferedReader reader;
public static void run()
{
try
{
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("connection");
while(running)
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
writer.println(line);
writer.flush();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
run();
}

Categories