How do i send an object to a server in java?
Client:
Help h = new Help("Mattia Cammalleri","Informatica","18 Novembre 2020");
Socket s = new Socket("localhost", 8888);
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
os.writeObject(h);
os.flush();
Server:
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
Help h = (Help) is.readObject();
System.out.println("Richiesta " + h);
Object (implements serializable):
public String alunno;
public String materia;
public String data;
Why it doesn't work?
I solved it in this way:
Client:
Help h = new Help("Mattia Cammalleri","Informatica","18 Novembre 2020");
Socket socket = new Socket("localhost", 7777);
System.out.println("Connected");
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
System.out.println("The object has been sent");
objectOutputStream.writeObject(h);
socket.close();
Server:
ServerSocket ss = new ServerSocket(7777);
System.out.println("Waiting for the client");
Socket socket = ss.accept();
System.out.println("Connected from " + socket + "!");
InputStream inputStream = socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Help h = (Help) objectInputStream.readObject();
System.out.println("Object: " + h);
ss.close();
socket.close();
Related
I'm trying to implement basic TCP communication via sockets and the problem is that it doesn't work. When I enter few sentences from client, the server receives only the first sentence and reply it back.
Client :
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 5055);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(!(sentence = inFromUser.readLine()).equals("end")) {
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
clientSocket.close();
Server:
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(5055);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
I am trying to pass message from server to client in terminal. What I would like the program to do is, in the client, it should be able to enter a command, get response from server, and be able to enter another command without restarting Client (by java Client).
Client.java
Socket socket = new Socket(host, port);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String response = "";
boolean continuation = true;
while(continuation) {
Scanner input = new Scanner(System.in);
String command = (input.nextLine()).toString();
bw.write(command+"\r\n");
bw.flush();
if(command.equals("cmd1") {
while ((response = br.readLine()) != null) {
System.out.println(response);
}
}
System.out.println("This line will not execute as well.");
}
Server.java
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String[] in = br.readLine().split("\\s+");
String command = in[0];
if(command.equals("cmd1")) {
String response = "";
response = response + "RESPONSE:\r\n";
response = response + "This is a response.\r\n";
bw.write(response);
bw.flush();
}
If I don't put while((response = br.readLine()!= null) { ... } in Client.java, it is possible to enter multiple inputs in the terminal, but if I put it, it prints the response from the server and another input cannot be done without restarting Client.
Any help would be appreciated.
Thanks
This should work:
server:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
boolean continuation = true;
while (continuation) {
String command = dis.readUTF();
//proceeed command
dos.writeUTF("response");
dos.flush();
}
Client:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("your command");
while (dis.available() == 0) {
try {
//wait for response
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(RandomTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
String response = dis.readUTF();
//and so on
Can anybody help me with this here. I am a newbie and I am working on a network application where I have to create a socket connection to the IP address and port that they already given me and then send XML message to the socket and finally include the ReadMe.txt file where I will save what I have received from the server. Here's my code
private static Socket socket;
public static void main(String args[])
{
try
{
socket = new Socket( "196.37.22.179", 9011);
//Send the message to the server
//PrintStream outstrm = null;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String str;
str = "<request>";
str += "<EventType>Authentication</EventType>";
str += "<event>";
str += "<UserPin>12345</UserPin>";
str += "<DeviceId>12345</DeviceId>";
str += "<DeviceSer>ABCDE</DeviceSer>";
str += "<DeviceVer>ABCDE</DeviceVer>";
str += "<TransType>Users</TransType>";
str += "</event></request>";
bw.write(str);
bw.flush();
System.out.println("Message sent to the server......! ");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
You can use this code to store results from server in file
//Get the return message from the server
InputStream is = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("ReadMe.txt"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
I am sending an image from my android gallery to a java server; however, I am getting a NegativeArraySizeException. Can anyone tell me what I am doing wrong? I do not understand what the problem is. Thanks in advance.
Android Client:
Socket sock;
sock = new Socket("IP", PORT);
System.out.println("Connecting...");
OutputStream os = sock.getOutputStream();
File myFile = new File (selectedImagePath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
Java Server
public class Receive {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
byte[] sizeAr = new byte[4];
InputStream inputStream = socket.getInputStream();
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
System.out.println(size); // getting negative value
byte[] imageAr = new byte[size];
inputStream.read(imageAr);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis());
ImageIO.write(image, "jpg", new File("C:/Users/Dan/Pictures/NewCat.jpg"));
serverSocket.close();
}
}
I need to make these code's multithreaded. I searched everywhere but i cant figure it out. Can you guys do it for me ?
Client.java's main method
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String senddata;
try{
clientSocket = new Socket("localhost",5555);
}catch(IOException e){
System.out.println("Connection Error!");
}
out = new PrintWriter(clientSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
BufferedReader data = new BufferedReader(new InputStreamReader(System.in));
while(!(senddata = data.readLine()).equals("STOP")){
out.println(senddata);
System.out.println("Response The Client = " + in.readLine());
System.out.print("------------------------------------------------------------\nEnter The Data That Will Send The Server = ");
}
out.close();
in.close();
data.close();
clientSocket.close();
Server.java's main method
ServerSocket serverSocket = null;
Socket clientSocket = null;
String receivedData;
try{
serverSocket = new ServerSocket(5555);
}catch(IOException e){
System.out.println("Port Error!");
}
clientSocket = serverSocket.accept(); // Bağlantıyı Sağlayan Kod Satırı. Bağlantı Sağlanmadan Bir Alt Satıra Geçilmez.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); // Clienta Veri Gönderimi İçin PrintWriter Nesnesi Oluşturuldu!
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Clientden Gelen Verileri Tutan BufferedReader Nesnesi Oluşturuldu!
while(!(receivedData = in.readLine()).equals("STOP")){
System.out.println("------------------------------------------------------------\nReceived Data From Client = " + receivedData);
System.out.println("Response = " + receivedData);
out.println(receivedData);
}
out.close();
in.close();
serverSocket.close();
clientSocket.close();