I've got the following code for my server:
try
{
Socket = serverSocket.accept();
inputStreamReader = new InputStreamReader(Socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
message = bufferedReader.readLine();
switch(message)
{
case "GET / HTTP/1.1":
{
break;
}
default:
{
System.out.println(message);
}
}
inputStreamReader.close();
Socket.close();
}
catch(Exception e)
{
System.out.println("Problem while waiting for messages (" + e.toString() + ")");
}
and this code for my (Android) Client:
private String GetPC(String strToPC)
{
final String strToPCFinal = strToPC;
Thread SendingThread = new Thread()
{
public void run()
{
try
{
client = new Socket("192.168.178.22", 14510);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(strToPCFinal);
printwriter.flush();
printwriter.close();
client.close();
}
catch(Exception e)
{
System.out.println("Problem while sending test message (" + e.toString() + ")");
}
}
};
SendingThread.start();
return "";
}
My question now is: How can I get an answer (if the text is successfully transmitted to my PC) back to my Android client?
private String readReply(SocketChannel socket) throws IOException {
final StringBuilder reply = new StringBuilder();
final ByteBuffer buffer = ByteBuffer.allocate(512);
int numBytesRead;
do {
numBytesRead = socket.read(buffer);
if (numBytesRead > 0) {
buffer.flip();
reply.append(decoder.decode(buffer).toString());
buffer.clear();
if (reply.indexOf(".") > -1) {
break;
}
}
} while (numBytesRead > -1);
socket.close();
return reply.toString();
}
Use the snippet below to send to server (if localhost)
private String send(String command) throws IOException {
final SocketAddress address = new InetSocketAddress("10.0.2.2", PORT);
final SocketChannel socket = SocketChannel.open(address);
final CharBuffer buffer = CharBuffer.wrap(command);
socket.write(encoder.encode(buffer));
final String reply = readReply(socket); // Get response
socket.close();
return reply;
}
Related
I´m creating a new socket to send a string through the socket, then the socket generates a reply (I monitor the reply in Wireshark) but in the code I cannot see any answer, only if I connect again to the socket with another app, then I receive the answer in the first socket connection.
public class TCPConnections
{
public static void main (String[] args) throws Exception
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
String response = "";
String hostGreetings = "<frame><cmd><id>5</id><hostGreetings><readerType>SIMATIC_RF680R</readerType><supportedVersions><version>V2.0</version></supportedVersions></hostGreetings></cmd></frame>\n";
String getReaderStatus = "<frame><cmd><id>2</id><getReaderStatus></getReaderStatus></cmd></frame>\n";
StringBuilder antwort = new StringBuilder();
int c;
int counter = 0;
try
{
String host = "30S50RFID01.w30.bmwgroup.net";
int port = 10001;
InetAddress address = InetAddress.getByName(host);
System.out.println("adress: " + address);
socket = new Socket(address, port);
System.out.println("Socket connected: " + socket.isConnected());
System.out.println("Remote Port: " + socket.getPort());
System.out.println("Traffic Class: " + socket.getTrafficClass());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
//byte [] bytes = hostGreetings.getBytes("UTF-8");
//System.out.println("UTF-8 = "+bytes);
if (socket.isConnected())
{
out.println(hostGreetings);
System.out.println("Message send:" + hostGreetings);
System.out.println("Message send:" + socket.getOutputStream());
System.out.println("Greeting sent, waiting for response");
Thread.sleep( 2000 );
boolean reading = true;
while (reading) {
if(in.ready ()){
c = (char) in.read();
response = response + c;
System.out.println("Reply" + response);
}else {
reading = false;
}
}
}
}
else
{
System.out.println("Socket connected: " + socket.isConnected());
}
}
catch (IOException ex)
{
System.out.println("Error 1: " + ex.getMessage());
}
catch (InterruptedException ex)
{
Logger.getLogger(TCPConnections.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{//Closing the socket
try
{
System.out.println("Connection will be closed and program terminated");
out.close();
in.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("Error 2: " + ex.getMessage());
}
}
}
}`
I'm creating my own server-software from scratch using this library.
Right now the client sends the server a Handshake packet, the server decodes it using a Handshake Codec and returns with a Response message encoded with a Response Codec, however I never get a Ping packet.
Here is my code for encoding the Response message to the server.
public class ResponseCodec implements Codec<ResponseMessage> {
#Override
public ResponseMessage decode(DataInputStream dataInputStream) {
String json = ByteUtilities.readUTF8(dataInputStream);
return new ResponseMessage(json);
}
#Override
public DataOutputStream encode(DataOutputStream dataOutputStream, ResponseMessage responseMessage) {
ByteArrayOutputStream packetArray = new ByteArrayOutputStream();
DataOutputStream packetStream = new DataOutputStream(packetArray);
ByteUtilities.writeVarInt(packetStream, 0x00);
ByteUtilities.writeUTF8(packetStream, responseMessage.getJson());
ByteUtilities.writeVarInt(dataOutputStream, packetArray.toByteArray().length);
try {
dataOutputStream.write(packetArray.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return dataOutputStream;
}
}
And here is my connection listener:
server.setConnectionListener(new ConnectionListener() {
#Override
public void onConnect(Socket socket, DataInputStream dataInputStream) throws Exception {
//header
int packetSize = ByteUtilities.readVarInt(dataInputStream);
int packetId = ByteUtilities.readVarInt(dataInputStream);
// writing handlers
OutputStream outputStream = socket.getOutputStream();
DataOutputStream socketStream = new DataOutputStream(outputStream);
//identification
if(packetId == 0x00) {
// decode
HandshakeCodec codec = new HandshakeCodec();
HandshakeMessage message = codec.decode(dataInputStream);
if(!(message.getProtocolVersion() == 47)) {
System.out.println("Client " + message.getAddress() + ":" + message.getPort() + " seems to have a incompatible client.");
}
ResponseCodec responseCodec = new ResponseCodec();
StringBuilder text = new StringBuilder();
BufferedReader formatReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("ResponseFormat.txt")));
String line = formatReader.readLine();
while (line != null) {
text.append(line);
text.append(System.lineSeparator());
line = formatReader.readLine();
}
String everything = text.toString();
String accountedWithVariables = everything
.replaceAll("MAX_PLAYERS", "" + maxPlayers)
.replaceAll("ONLINE_PLAYERS", "" + BasicServer.onlinePlayers)
.replaceAll("MOTD", motd);
ResponseMessage responseMessage = new ResponseMessage(accountedWithVariables);
responseCodec.encode(socketStream, responseMessage);
}
if(packetId == 0x01) {
long pingLong = dataInputStream.readLong();
PongCodec codec = new PongCodec();
PongMessage message = new PongMessage(pingLong);
codec.encode(socketStream, message);
}
}
#Override
public void onCaughtException(Exception e) {
System.out.println("Main thread has recieved a exception: " + e.getMessage());
e.printStackTrace();
}
});
This question already has answers here:
Why fileOutputStream can't output any string after an empty line (or a line break) in client-server application?
(2 answers)
Closed 7 years ago.
In my client-server application, when I try to download a file from the serverSide, the file gets downloaded; but the header information such as some additional text with line break can't be read. As you can see in my Server class this following information is supposed to be printed out in the client side.
outputToClient.printf("Status OK\r\nSize %d Bytes\r\n\r\nFile %s Download was successfully\r\n",
fileSize, filename);
But it doesn't. Only the fisrt string (Status OK) before the \r\n gets printed, not any string after \r\n.
How can I fix it?
My complete code:
ServerSide:
public class ServerSide {
private BufferedReader inputFromClient;
private PrintWriter outputToClient;
private FileInputStream fis;
private OutputStream os;
private static final int PORT = 8000;
private ServerSocket serverSocket;
private Socket socket;
public static void main(String[] args) {
int port = PORT;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
}
new ServerSide(port);
}
private boolean fileExists(File[] files, String filename) {
boolean exists = false;
for (File file : files) {
if (filename.equals(file.getName())) {
exists = true;
}
}
return exists;
}
public ServerSide(int port) {
// create a server socket
try {
serverSocket = new ServerSocket(port);
} catch (IOException ex) {
System.out.println("Error in server socket creation.");
System.exit(1);
}
while (true) {
try {
socket = serverSocket.accept();
outputToClient = new PrintWriter(socket.getOutputStream());
inputFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String request = inputFromClient.readLine();
if (!request.startsWith("exit") && !request.startsWith("pwd") && !request.startsWith("list") && !request.startsWith("GET")) {
outputToClient.println("Wrong request\r\n"
+ "\r\n");
} else if (request.startsWith("exit")) {
break;
} else if (request.startsWith("pwd")) {
File file = new File(System.getProperty("user.dir"));
outputToClient.print("Status OK\r\n"
+ "Lines 1\r\n"
+ "\r\n"
+ "Working dir: " + file.getName() + "\r\n");
} else if (request.startsWith("list")) {
File file = new File(System.getProperty("user.dir"));
File[] files = file.listFiles();
outputToClient.print("Status OK\r\n"
+ "Files " + files.length + "\r\n"
+ "\r\n"
+ Arrays.toString(files).substring(1, Arrays.toString(files).length() - 1) + "\r\n");
} else if (request.startsWith("GET")) {
String filename = request.substring(4);
File file = new File(System.getProperty("user.dir"));
File[] files = file.listFiles();
if (fileExists(files, filename)) {
file = new File(filename);
int fileSize = (int) file.length();
outputToClient.printf("Status OK\r\nSize %d Bytes\r\n\r\nFile %s Download was successfully\r\n",
fileSize, filename);
outputToClient.flush();
try (FileInputStream fis = new FileInputStream(file)) {
os = socket.getOutputStream();
byte[] buffer = new byte[(1 << 7) - 1];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
//os.close();
// fis.close();
} else {
outputToClient.print("Status 400\r\n"
+ "File " + filename + " not found\r\n"
+ "\r\n");
outputToClient.flush();
}
}
outputToClient.flush();
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
ClientSide:
public class ClientSide {
private static Socket socket;
private static PrintWriter outputToServer;
private static BufferedReader inputFromServer;
private static InputStream is;
private static FileOutputStream fos;
private static final int PORT = 8000;
private static final String SERVER = "85.197.159.45";
boolean Connected;
DataInputStream serverInput;
public static void main(String[] args) throws InterruptedException {
String server = "localhost";
int port = PORT;
if (args.length >= 1) {
server = args[0];
}
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
new ClientSide(server, port);
}
public ClientSide(String server, int port) {
try {
socket = new Socket(server, port);
serverInput = new DataInputStream(socket.getInputStream());
outputToServer = new PrintWriter(socket.getOutputStream(), true);
inputFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Client is connected! ");
Connected = true;
String line = null;
Scanner sc = new Scanner(System.in);
System.out.print("Type command: ");
while (sc.hasNextLine()) {
String request = sc.nextLine();
if (request.startsWith("exit")) {
outputToServer.println(request);
System.out.println("Application exited!");
//outputToServer.flush();
break;
} else if (request.startsWith("pwd")) {
outputToServer.println(request);
outputToServer.flush();
} else if (request.startsWith("list")) {
outputToServer.println(request);
outputToServer.flush();
} else if (request.startsWith("GET")) {
System.out.print("\r\n");
outputToServer.println(request);
outputToServer.flush();
}
while (Connected) {
line = inputFromServer.readLine();
System.out.println(line);
if (line.isEmpty()) {
Connected = false;
if (inputFromServer.ready()) {
System.out.println(inputFromServer.readLine());
}
}
if (line.startsWith("Status 400")) {
while (!(line = inputFromServer.readLine()).isEmpty()) {
System.out.println(line);
}
break;
}
if (request.startsWith("GET")) {
File file = new File(request.substring(4));
is = socket.getInputStream();
fos = new FileOutputStream(file);
byte[] buffer = new byte[socket.getReceiveBufferSize()];
serverInput = new DataInputStream(socket.getInputStream());
//int bytesReceived = 0;
byte[] inputByte = new byte[4000];
int length;
while ((length = serverInput.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length);
}
request = "";
fos.close();
}
}
System.out.print("\nType command: ");
Connected = true;
}
outputToServer.close();
inputFromServer.close();
socket.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
You should close the output stream outputToClient.close() after final outputToClient.flush()
I'm trying to make a chat application in java, but I had a problem, when I couldn't send to another machine.
Here's part of my codes:
This is my class client:
public class EnvioSocket {
public static boolean enviarSocket(String nome, String ip, int porta,
String mensagem) {
String dados = nome + " : " + mensagem;
try {
Socket socket = new Socket(ip, porta);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(dados);
out.close();
socket.close();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
}
return true;
}
}
This is my class server:
public class ServidorThread implements Runnable {
private JTextArea menssage;
public ServidorThread(JTextArea menssage) {
this.menssage = menssage;
}
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(Porta.PORTA);
while (true) {
Socket acceptedSocket = serverSocket.accept();
DataInputStream in = new DataInputStream(
acceptedSocket.getInputStream());
String menssage = in.readUTF();
this.menssage.append(DateUtils.dateToString(new Date(), "dd/MM/yyyy HH:mm") + " " + menssage + "\n");
in.close();
acceptedSocket.close();
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
define a port to socket
public final class Porta {
private Porta() {
}
public static final int PORTA = 6066;
}
I can only send a message to my own computer. How can I fix this?
I'm starting my thread inside of my class that make a GUI.
It looks like you've set up your Server right, but your client doesn't seem to ever connect to it. You need to create a socket which will connect to the server socket. This socket can then give you I/O streams to send data through.
Java's tutorial, complete with code examples
The question is not that simple to me...I can show you the basics for client server echo application in java...You can expand on that to make a chat session between to clients I suppose...here it goes...
public class MultiThreadServer implements Runnable {
Socket csocket;
private static boolean quitFlag = false;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (!quitFlag) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
String action = in.readLine();
PrintStream pstream = new PrintStream(csocket.getOutputStream());
System.out.printf("Server received... " + action + " ...action\n");
switch (action) {
case "bottle":
for (int i = 3; i >= 0; i--) {
pstream.println("<p>" + i + " bottles of beer on the wall" + "</p>");
}
pstream.println("<p>" + action + "</p>");
break;
case "echo":
pstream.println("<p>" + action + "</p>");
break;
case "quit":
quitFlag = true;
break;
}
pstream.close();
csocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Running the server to echo your response is easy...making the client or clients are more challenging...simple jsp Client..
<BODY>
<H1>Creating Client/Server Applications</H1>
<%
String serverInput = request.getParameter("serverInput");
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
InputStream inSocket = socket.getInputStream();
OutputStream outSocket = socket.getOutputStream();
String str = serverInput+"\n";
byte buffer[] = str.getBytes();
outSocket.write(buffer);
while ((character = inSocket.read()) != -1) {
out.print((char) character);
}
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</BODY>
or better yet...
<body>
<%String name = request.getParameter("inputString");%>
<h1>Creating Client Applications</h1>
<p>Client Sent... <%=name%> ...to Server</p>
<%
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
OutputStream outSocket = socket.getOutputStream();
String str = name;
byte buffer[] = str.getBytes();
outSocket.write(buffer);
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</body>
I am facing problem in Java socket communication, I am running Live555 Media Server and one small app (some what similar to proxy server code, referred one online code snippet) in one machine, and also created one client code and running in my laptop. All machines are in same network. When I send RTSP Command from client to proxy, It is receiving properly and it is redirecting that received command to Live555 server and its getting back proper response but the response is not receiving in client. Help me to fix this problem and also suggest me some doc link to understand the problem.
here is my proxy code,
public class TestProxyServer {
public static void main(String[] args) {
try {
String host = "127.0.0.1";
int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting proxy for " + host + ":" + serverPort
+ " on port " + proxyPort);
runServer(host, serverPort, proxyPort);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sProt, int pPort) throws IOException {
ServerSocket ss = new ServerSocket(pPort);
final byte[] request = new byte[1024];
byte[] replay = new byte[1024];
while(true) {
Socket server = null, client = null;
try {
client = ss.accept();
final InputStream fromClient = client.getInputStream();
final OutputStream toClient = client.getOutputStream();
// for Live555
try {
server = new Socket(host, sProt);
} catch(Exception e) {
PrintWriter out = new PrintWriter(toClient);
out.print("Proxy can not connect to Live555 on host " + host + " with the port " + sProt + "\n");
out.flush();
client.close();
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String ClientMSG;
while((bytesRead = fromClient.read(request)) != -1) {
toServer.write(request, 0, bytesRead);
ClientMSG = new String(request, 0, bytesRead);
System.err.println("From Client : " + ClientMSG);
toServer.flush();
}
} catch(Exception e) {
try {toServer.close();} catch(IOException ioe){}
}
}
};
t.start();
int bytesRead;
try {
String toCMSG;
while((bytesRead = fromServer.read(replay)) != -1) {
toClient.write(replay, 0, bytesRead);
toCMSG = new String(replay, 0, bytesRead);
System.err.println("Response from Live555 " + toCMSG);
toClient.flush();
}
} catch(Exception e) {
toClient.close();
// e.printStackTrace();
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(server != null)
server.close();
if(client != null)
client.close();
}
}
}
}
and client code is here,
public class Test {
public static void main(String[] args) {
try {
String host = "192.168.1.9";
// int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting Client to connect proxy on " + host + ":" + " with port " + proxyPort);
runServer(host, proxyPort);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sPort) throws IOException {
final byte[] request = new byte[1024];
final byte[] reply = new byte[1024];
while (true) {
Socket server = null;
try {
// for Proxy
try {
server = new Socket(host, sPort);
} catch (Exception e) {
System.out.println("Proxy can not connect to ProxyServer on host " + host + " with the port " + sPort + "\n");
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
int bytesRead;
try {
String RtspMSG = "DESCRIBE rtsp://192.168.1.9:8554/free.ts RTSP/1.0\r\nCSeq: 2\r\n\r\n";
// while((bytesRead = fromClient.read(RtspMSG.getBytes()))
// != -1) {
toServer.write(RtspMSG.getBytes(), 0, RtspMSG.length());
System.err.println("Sent : " + RtspMSG);
toServer.flush();
// }
} catch (Exception e) {
try {
toServer.close();
} catch (IOException ioe) {
}
}
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String response = null;
System.err.println("----------------------------------");
while ((bytesRead = fromServer.read(reply)) != -1) {
response = new String(reply, 0, bytesRead);
}
System.err.println("Response from Proxy : "
+ response);
} catch (Exception e) {
try {
fromServer.close();
} catch (Exception e1) {
}
// e.printStackTrace();
}
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (server != null)
server.close();
}
}
}
}
Thank You