TCP Server and Client in Java - java

I tried building a TCP server and client using Java. They can connect, they work well, but I have a single error.
This is the server side:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main (String[] args) throws IOException {
System.out.println("The server is ready");
ServerSocket serverSocket = new ServerSocket (1234);
Socket clientSocket = serverSocket.accept ();
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message, modifiedMessage;
message = in.readLine ();
System.out.print("The received message from client: " + message);
modifiedMessage = message.toUpperCase();
out.print(modifiedMessage);
System.out.println ("\nModified message which is sent to client: " + modifiedMessage);
}
}
The server will have to receive a message from a client, then transforming it in an upper case string.
The client side is:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter a lowercase sentence: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader((new InputStreamReader(socket.getInputStream())));
String messageSent = reader.readLine();
System.out.println("The message sent is: " + messageSent);
out.println(messageSent);
String messageReceived = in.readLine();
System.out.println("The modified message is: " + messageReceived);
}
}
I want the client to be able to print both the lower case sentence and the received (modified) upper case sentence. The problem is that, when I enter a simple word, say hello, my client will only print the original string, not the modified one.
The output of the server is:
The received message from client: hello
The modified message sent to the client is: HELLO
But the output of the client is:
The message sent is: hello
The modified message is: null
I know that the server is able to convert the string to the upper-case version and to connect to my client. Why doesn't my client print the received message? Doesn't it actually receive it?

You need to flush the message. PrintWriter calls flush in println, print doesn't.
on the server side you need to change to:
out.println(modifiedMessage);
instead of
out.print(modifiedMessage);

Related

Whenever I run my server on the specified port, it returns illegible characters. Why?

I am running a client server program on port 80 (currently says port 2040 for testing purposes only). Whenever I run my server on my client side/browser, the console displays this weird text, when it should be returning a HTMl file that i scannned in. However, when I run my IP address on my browser, it returns the necessary code. Why?
Here is my code:
public class ServerSide {
public static void main(String[] args) throws Exception {
//port used
int port = 2040;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Running on port " +port);
/*server always on
* creating a connection socket when contacted by client..
*/
while(true) {
//create connection socket when contacted
Socket client = serverSocket.accept();
//read input from client
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
//whatever input or communication we want to have can operate in this string..
String x;
while((x = input.readLine()) != null){
System.out.println(x);
if(x.isEmpty()) {
break;
}
}
//output of client server..
OutputStream clientOutput = client.getOutputStream();
clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes());
clientOutput.write("\r\n".getBytes());
clientOutput.write("".getBytes());
clientOutput.write("\r\n\r\n".getBytes());
Scanner fetch = new Scanner(new File("index.html"));
String myHTML_file = fetch.useDelimiter("\\Z").next();
fetch.close();
clientOutput.write(myHTML_file.getBytes("UTF-8"));
clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();
System.out.println("Connection closed.");
clientOutput.close();
}
}
}

write with Python client to Java server

I am trying to combine Python and Java using a socket connection. I hava a Java server and a Python client. They are able to connect to each other, and the server is able to write to the client, but when I try to send a message from the client to the server, it throws an EOFException. What should I do to get this to work?
Server code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serversocket = new ServerSocket(6000);
Socket client = serversocket.accept();
final DataInputStream input = new DataInputStream(client.getInputStream());
final DataOutputStream output = new DataOutputStream(client.getOutputStream());
output.writeUTF("Hello Client!");
String message = (String)input.readUTF();
System.out.println(message);
serversocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client code:
import socket
socket = socket.socket()
host = "localhost"
port = 6000
socket.connect((host, port))
message = socket.recv(1024)
print(message.decode())
socket.sendall("Hello Server".encode())
socket.close()
The exception:
java.io.EOFException
at java.base/java.io.DataInputStream.readFully(DataInputStream.java:203)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:615)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:570)
at Server.main(Server.java:19)
Option #1:
Replace input.readUTF() in server with this:
while(true) {
int ch = input.read();
if (ch == -1) break;
System.out.print((char)ch);
}
Option #2:
If want to read UTF-encoded strings (vs plain ASCII) on server then recommend using BufferedReader with utf-8 charset and readLine().
ServerSocket serversocket = new ServerSocket(6000);
System.out.println("Waiting for connections");
Socket client = serversocket.accept();
final BufferedReader input = new BufferedReader(
new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); // changed
final OutputStream output = client.getOutputStream();
//output.writeUTF("Hello Client!"); // see note below
output.write("Hello Client!".getBytes(StandardCharsets.UTF_8)) // changed
String message = input.readLine(); // changed
System.out.println(message);
client.close();
serversocket.close();
Client output:
Hello Client!
Server output:
Hello Server
Note JavaDoc of DataOutputStream#writeUTF(...) says:
First, two bytes are written to the output stream as if by the
writeShort method giving the number of bytes to follow.
Using output.write(s.getBytes(StandardCharsets.UTF_8)) is more compatible with non-Java clients. Python utf-8 decoding doesn't support the 2-byte length prefix added by writeUTF().
Finally, if want the server to handle more than one client connection, then add a loop that encloses the code after ServerSocket is created and only close the client socket inside the loop.

Simple Java Networking Program

I'm new to Java programming and I'm just trying to get a very basic networking program to work.
I have 2 classes, a client and a server. The idea is the client simply sends a message to the server, then the server converts the message to capitals and sends it back to the client.
I'm having no issues getting the server to send a message to the client, the problem is I can't seem to store the message the client is sending in a variable server side in order to convert it and so can't send that specific message back.
Here's my code so far:
SERVER SIDE
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket (9091);
while (true) {
System.out.println("Waiting");
//establish connection
Socket client = server.accept();
System.out.println("Connected " + client.getInetAddress());
//create IO streams
DataInputStream inFromClient = new DataInputStream(client.getInputStream());
DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
System.out.println(inFromClient.readUTF());
String word = inFromClient.readUTF();
outToClient.writeUTF(word.toUpperCase());
client.close();
}
}
}
CLIENT SIDE
public class Client {
public static void main(String[] args) throws IOException {
Socket server = new Socket("localhost", 9091);
System.out.println("Connected to " + server.getInetAddress());
//create io streams
DataInputStream inFromServer = new DataInputStream(server.getInputStream());
DataOutputStream outToServer = new DataOutputStream(server.getOutputStream());
//send to server
outToServer.writeUTF("Message");
//read from server
String data = inFromServer.readUTF();
System.out.println("Server said \n\n" + data);
server.close();
}
}
I think the problem might be with the 'String word = inFromClient.readUTF();' line? Please can someone advise? Thanks.
You're discarding the first packet received from the client:
System.out.println(inFromClient.readUTF()); // This String is discarded
String word = inFromClient.readUTF();
Why not swap these?
String word = inFromClient.readUTF(); // save the first packet received
System.out.println(word); // and also print it

SMTP and Java email error

Hello I worked on this code to figure out how SMTP works with a java program and I got really far but I keep getting this error and I dont know whats wrong with it. It all seams to be what other similar programs that I looked at do but theirs seems to work.
It gets all the way down to the FROM line and then prints out this error
530 5.7.0 Must issue a STARTTLS command first. n1sm21348109bkv.14 - gsmtp
Exception in thread "main" java.lang.Exception: 250 reply not received from server.
at emailagent.EmailAgent.main(EmailAgent.java:73)
Any help with this would be appreciated
Thanks
import java.io.*;
import java.net.*;
import java.util.*;
public class EmailAgent
{
public static void main(String[] args) throws Exception
{
// Establish a TCP connection with the mail server.
System.out.println("Enter the mail server you wish to connect to (example: pop.gmail.com):\n");
String hostName = new String();
Scanner emailScanner = new Scanner(System.in);
hostName = emailScanner.next();
Socket socket = new Socket(hostName, 25);
// Create a BufferedReader to read a line at a time.
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// Read greeting from the server.
String response = br.readLine();
System.out.println(response);
if (!response.startsWith("220"))
{
throw new Exception("220 reply not received from server.");
}
// Get a reference to the socket's output stream.
OutputStream os = socket.getOutputStream();
// Send HELO command and get server response.
String command = "HELO alice\r\n";
System.out.print(command);
os.write(command.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.");
}
// Send HELO command and get server response.
System.out.println("Enter the name of your mail domain (example: hotmail.com):");
String heloDomain = emailScanner.next();
String fullHeloCommand = "HELO " + heloDomain + "\r\n";
System.out.print(fullHeloCommand);
os.write(fullHeloCommand.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.\n");
}
// Send MAIL FROM command.
System.out.println("Please enter your e-mail address (example: me#myexample.com:\n");
String sourceAddress = emailScanner.next();
String mailFromCommand = "MAIL FROM: <" + sourceAddress + ">\r\n";
System.out.println(mailFromCommand);
os.write(mailFromCommand.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.\n");
}
// Send RCPT TO command.
System.out.println("Please type the destination e-mail address (example: example#nova.edu):\n");
String destEmailAddress = new String();
destEmailAddress = emailScanner.next();
String fullAddress = new String();
fullAddress = "RCPT TO: <" + destEmailAddress + ">\r\n";
System.out.println(fullAddress);
os.write(fullAddress.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if(!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.\n");
}
// Send DATA command.
String dataString = new String();
dataString = "DATA";
System.out.println(dataString);
os.write(dataString.getBytes("US-ASCII"));
response = br.readLine();
if(!response.startsWith("354"))
{
throw new Exception("354 reply not received from server.\n");
}
System.out.println(response);
// Send message data.
System.out.println("Enter your message, enter '.' on a separate line to end message data entry:\n");
String input = new String();
while(input.charAt(0) != '.')
{
input = emailScanner.next();
os.write(input.getBytes("US-ASCII"));
}
//End with line with a single period.
os.write(input.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if(!response.startsWith("250"))
{
throw new Exception("250 reply not received from server\n");
}
// Send QUIT command.
String quitCommand = new String();
quitCommand = "QUIT";
os.write(quitCommand.getBytes("US-ASCII"));
}
}
The mail server you are attempting to connect to requires you establish a secure connection (TLS) in order to use mail services. Thats the error you are getting.
As far as the solution, I would highly recommend using the JavaMail library as it provides much of this functionality out of the box, and has been robustly tested 'in the wild'.

Socket java client-server

I have to build a server and a client in Java. The server opens a connection on port 18163. The client connects to the server and establishes a number X, the server sends the message "guess", the server received the message repeatedly attempts to determine the value of X to the client sending the message "I feel Y" where Y is the value of a integer. When the client receives the message "I feel Y" sends to the server: "Same" if the number is correct, "Not equal if the number is not correct." If the number is correct, the server sends the client the "Close" and the client closes the connection.
I have to implement this program without the use of thread! I tried that, but it doesn't work.
CLIENT:
public class Client{
public static void main(String[] args)throws Exception{
Socket c= new Socket("127.0.0.1",18163);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(c.getInputStream()));
DataOutputStream outToServer=new DataOutputStream(c.getOutputStream());
int min=1,max=10;
String frase;
int n1;
int numcasuale=(min+(int)(Math.random()*((max - min)+1)));
System.out.println("Num casuale generato: "+numcasuale);
do{
frase=inFromServer.readLine();
n1=Integer.parseInt(frase);
System.out.println("DAL SERVER: PROVO "+n1);
}while(!(n1==numcasuale));
outToServer.writeBytes("UGUALE\n");
frase=inFromServer.readLine();
if(frase.equals("CLOSE")){
System.out.println("Esecuzione terminata.");
c.close();
}
}
}
SERVER:
public class Server{
public static void main(String[] args)throws Exception{
ServerSocket ss = new ServerSocket(18163);
int min=1,max=10,numcasuale;
String dallclient;
while(true){
Socket c= ss.accept();
System.out.println("Client connesso: "+ c.getRemoteSocketAddress());
DataOutputStream alclient=new DataOutputStream(c.getOutputStream());
BufferedReader dalclient =new BufferedReader(new InputStreamReader(c.getInputStream()));
dallclient= dalclient.readLine();
System.out.println("DAL CLIENT :"+dallclient);
do{
numcasuale=(min+(int)(Math.random()*((max - min)+1)));
alclient.write(numcasuale);
dallclient= dalclient.readLine();
System.out.println("DAL CLIENT: "+dallclient);
}while(!(dallclient.equals("UGUALE")));
}alclient.writeBytes("CLOSE\n");
}
}
I think in the server part you are missing an \n at this line:
while( !(dallclient.equals("UGUALE")) );
since the client is sending "UGUALE\n"
outToServer.writeBytes("UGUALE\n");

Categories