Java Sockets TCP send and receive -
i tried many examples , none worked expect. need?
- send packet through ip , port.
- wait until server response , close socket.
example:
[client] send: "hi server" [client] wait [server] send: "hi client" [client] receive response [client] close socket
i need tcp client, server side solved.
tried: http://www.careerbless.com/samplecodes/java/beginners/socket/socketbasic1.php
my code
public class sendpacket { public void send() throws exception{ socket socket = null; objectoutputstream oos = null; objectinputstream ois = null; socket = new socket(ip, port); oos = new objectoutputstream(socket.getoutputstream()); string msg = "dspsyssts"; oos.write(msg.getbytes()); oos.flush(); //read server response message ois = new objectinputstream(socket.getinputstream()); string message = (string) ois.readobject(); runwincmd runcmd = new runwincmd(); runcmd.run("notepad.exe \"" + message + "\""); //close resources ois.close(); oos.close(); } }
you have initialise streams in particular order.
try (not tested):
public class sendpacket { public void send() throws exception{ socket socket = null; objectoutputstream oos = null; objectinputstream ois = null; socket = new socket(ip, port); oos = new objectoutputstream(socket.getoutputstream()); ois = new objectinputstream(socket.getinputstream()); string msg = "dspsyssts"; oos.write(msg.getbytes()); oos.flush(); //read server response message string message = (string) ois.readobject(); runwincmd runcmd = new runwincmd(); runcmd.run("notepad.exe \"" + message + "\""); //close resources ois.close(); oos.close(); socket.close();//!!!! } }
Comments
Post a Comment