I'm trying to get a live flash that lives on a webserver to talk to a local java server, that will live on the clients PC.
I'm trying to achieve this with a socket connection. (port 6000)
Now, at first flash was able to connect, but it just sends <policy-file-request/>. After this nothing happens.
Now, some people at Kirupa suggested to send an cross-domain-policy xml as soon as any connection is established from the java side. http://www.kirupa.com/forum/showthread.php?t=301625
However, my java server just throws the following:
End Exception: java.net.SocketException: Software caused connection abort: recv failed
I've already spend a great amount of time on this subject, and was wondering if anyone here knows what to do?
I found the anwser, So ill post it here in case someone with a simmilar question finds this post.
The moment Flash connects to a local socket server it will send the following:
<policy-file-request/>
We will have to answer with a policy file and immediatly close the connection.
Java:
import java.net.*;
import java.io.*;
public class NetTest {
public static void main(String[] args) {
ServerSocket serverSocket = null;
/* Open a socket to listen */
try {
serverSocket = new ServerSocket(6000);
} catch (IOException e) {
System.out.println("Could not listen on port: 6000");
System.exit(-1);
}
// Try catch a socket to listen on
Socket clientSocket = null;
try {
System.out.println("Waiting for auth on 6000...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 6000");
System.exit(-1);
}
// Now a stream has been opened...
InputStream in = null;
OutputStream out = null;
try {
in = clientSocket.getInputStream();
out = clientSocket.getOutputStream();
} catch (IOException e) {
System.out.println("Failed to get streams.");
System.exit(-1);
}
System.out.println("Socket connection incoming!");
// Keep going while we can...
byte b[] = new byte[100];
int offset = 0;
String s;
try {
boolean done = false;
boolean auth = false;
String protocol_target = "<policy-file-request/>";
byte[] p_bytes = protocol_target.getBytes();
int result;
while (!done) {
if (in.read(b, offset, 1) == -1)
done = true;
else {
if (!auth) {
++offset;
b[offset] = 0;
if (offset != p_bytes.length) {
System.out.println("Waiting for protocol data... ("
+ offset + "/" + p_bytes.length + ")");
} else {
// Compare byte data
for (int i = 0; i < p_bytes.length; ++i) {
System.out.print(b[i] + " ");
}
System.out.print("\n");
System.out.flush();
for (int i = 0; i < p_bytes.length; ++i) {
System.out.print(p_bytes[i] + " ");
}
System.out.print("\n");
System.out.flush();
boolean match = true;
for (int i = 0; i < p_bytes.length; ++i) {
if (b[i] != p_bytes[i]) {
match = false;
System.out
.println("Mismatch on " + i + ".");
}
}
if (match)
auth = true;
else {
System.out.println("Bad protocol input.");
System.exit(-1);
}
}
// Auth
if (auth) {
System.out.println("Authing...");
s = "<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain='*' to-ports='6000' /></cross-domain-policy>";
b = s.getBytes();
out.write(b, 0, b.length);
b[0] = 0;
out.write(b, 0, 1); // End
out.flush();
offset = 0;
b = new byte[100];
b[0] = 0;
auth = true;
System.out.println("Auth completed.");
}
}
}
}
} catch (IOException e) {
System.out.println("Stream failure: " + e.getMessage());
System.exit(-1);
}
// Finished.
try {
in.close();
out.close();
clientSocket.close();
} catch (Exception e) {
System.out.println("Failed closing auth stream: " + e.getMessage());
System.exit(-1);
}
// Try catch a socket to listen on for data
try {
System.out.println("Waiting on 6000 fo data...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 6000");
System.exit(-1);
}
// Now a stream has been opened...
in = null;
out = null;
try {
in = clientSocket.getInputStream();
out = clientSocket.getOutputStream();
} catch (IOException e) {
System.out.println("Failed to get streams.");
System.exit(-1);
}
System.out.println("Socket data connection waiting.");
// Echo
try {
boolean done = false;
while (!done) {
if (in.read(b, offset, 1) == -1)
done = true;
else {
b[1] = 0;
s = new String(b);
System.out.print(s);
System.out.flush();
}
}
} catch (IOException e) {
System.out.println("Failed echo stream: " + e.getMessage());
System.exit(-1);
}
// Finished.
try {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (Exception e) {
System.out.println("Failed closing stream: " + e.getMessage());
System.exit(-1);
}
}
}
Related
this code is giving me some problems. This's simply the thread portion of a Service that receive data sent trough a TCP connection. This data is an image (160x120x16bpp = 38400 bytes) feed to an Activity trough a callback.
public void run() {
InetAddress serverAddr;
link_respawn = 0;
try {
serverAddr = InetAddress.getByName(VIDEO_SERVER_ADDR);
} catch (UnknownHostException e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
return;
}
Socket socket = null;
DataInputStream stream;
do {
bad_frames = 0;
frames = 0;
status = FrameDecodingStatus.Idle;
try {
socket = new Socket(serverAddr, VIDEO_SERVER_PORT);
stream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
final byte[] _data = new byte[PACKET_SIZE];
final byte[] _image_data = new byte[IMAGE_SIZE];
int _data_index = 0;
while (keepRunning) {
if (stream.read(_data, 0, _data.length) == 0)
continue;
for (byte _byte : _data) {
if (status == FrameDecodingStatus.Idle) {
if (_byte == SoF) {
status = FrameDecodingStatus.Data;
_data_index = 0;
}
} else if ((status == FrameDecodingStatus.Data) && (_data_index < IMAGE_SIZE)) {
_image_data[_data_index] = _byte;
_data_index++;
} else if ((status == FrameDecodingStatus.Data) && (_data_index == IMAGE_SIZE)) {
if (_byte == EoF) {
if(frameReadyCallBack!=null)
frameReadyCallBack.frameReady(_image_data);
frames++;
status = FrameDecodingStatus.Idle;
}
}
}
}
link_respawn++;
Thread.sleep(VIDEO_SERVER_RESPAWN);
Log.d(getClass().getName(), "Link respawn: " + link_respawn);
} catch (Throwable e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
}
} while (keepRunning);
if (socket != null) {
try {
socket.close();
} catch (Throwable e) {
Log.e(getClass().getName(), e.getMessage());
e.printStackTrace();
}
}
}
the Android Activity that receive the callback find data in array corrupted in a very strange way .. i.e. starting at a certain index data into array is set to 0.
How can I avoid this?
read is not readFully. Three-arg read returns the number of bytes that has been read, which is not necessary the full length of the array supplied.
This codes drops the read return value and process the entire array.
if (stream.read(_data, 0, _data.length) == 0)
continue;
for (byte _byte : _data) {
I'm working on a multi-threaded web-server for a school project. I should be able to go into the localhost on my browser and request 3 different files (.htm, .jpeg,.pdf). However, when I do this for a .htm file with the picture also inside of it (2 requests) the .htm file appears in browser but I get many broken pipe socket exceptions for each write I try to do on the picture (Assignment requires to write 1024 bytes at a time). Something is clearly wrong with the way I have implemented this but I am at a loss as to where the connection is being closed when I try to write for the second file?
I tried a few different things to try and fix this including a loop when trying to read the socket input stream but I think that defeats the purpose of the multi-threaded server.
The server:
while(true){
try {
sock = servSock.accept(); // Handles the connection
// Connection received log
System.out.println("Connection received: " + new Date().toString() + " at " + sock.getInetAddress() + sock.getPort());
HTTP pro = new HTTP(sock); // Client handler
pro.run();
ServerThread serverThread = new ServerThread(pro);
// Starts ServerThread
serverThread.start();
} catch (Exception e){
System.out.println(e);
}
}
HTTP:
public void run(){
// Try to open reader
try{
readSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (Exception e){
System.out.println(e);
}
// Open output stream
try{
this.out = new DataOutputStream(sock.getOutputStream());
this.printOut = new PrintWriter(sock.getOutputStream());
} catch (Exception e){
System.out.println(e);
}
// Try to read incoming line
try {
this.reqMes = readSock.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(reqMes);
// Parse the request message
int count = 0;
while(st.hasMoreTokens()){
String str = st.nextToken();
if (count == 1){
this.fileName = "." + str;
}
count += 1;
}
System.out.println("File name received.");
File file = null;
try {
file = new File(this.fileName);
this.f = new FileInputStream(file); // File input stream
this.fileExists = true;
System.out.println("File " + this.fileName + " exists.");
} catch (FileNotFoundException e) {
System.out.println(e);
this.fileExists = false;
System.out.println("File does not exist.");
}
byte[] buffer = new byte[1024];
// Write status line
if (this.fileExists) {
System.out.println("Trying to write data");
try{
this.out.writeBytes("HTTP/1.0 " + "200 OK " + this.CRLF);
this.out.flush();
this.printOut.println("HTTP/1.0 " + "200 OK " + this.CRLF);
// Write Header
this.out.writeBytes("Content-type: " + getMime(this.fileName) + this.CRLF);
this.printOut.println("Content-type: " + getMime(this.fileName) + this.CRLF);
this.out.flush();
// Read file data
byte[] fileData = new byte[1024];
while (this.f.read(fileData) != -1) {
// Write File data
try{
this.out.write(fileData,0,1024);
this.out.flush(); // Flush output stream
} catch (IOException e) {
System.out.println(e);
}
}
System.out.println("Flushed");
} catch (IOException e) {
e.printStackTrace();
}
}
For one .htm file in the browser, the file and html seem to appear fine. But it looks like it makes a second request for a .jpeg file within the html file and the browser gets stuck loading with java.net.SocketException: Broken pipe (Write failed) when writing the data each time at
this.out.write(fileData,0,1024);
Thank you, any help is appreciated.
After much searching among different problems, I found the answer here.
The problem was with the response headers not being formatted properly which led to the connection ending prematurely. Another empty line ("\r\n") must be sent after the header.
The following code now works (this.CRLF is equal to "\r\n"):
public void run(){
// Try to open reader
try{
readSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (Exception e){
System.out.println(e);
}
// Open output stream
try{
this.out = new DataOutputStream(sock.getOutputStream()); // Data output
this.printOut = new PrintWriter(sock.getOutputStream()); // Print output
} catch (Exception e){
System.out.println(e);
}
// Try to read incoming line
try {
this.reqMes = readSock.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(reqMes);
// Parse the request message
int count = 0;
while(st.hasMoreTokens()){
String str = st.nextToken();
if (count == 1){
this.fileName = "." + str;
}
count += 1;
}
System.out.println("File name received.");
// Initialize file to be sent
File file = null;
// Try to find file and create input stream
try {
file = new File(this.fileName);
this.f = new FileInputStream(file); // File input stream
this.fileExists = true;
System.out.println("File " + this.fileName + " exists.");
} catch (FileNotFoundException e) {
System.out.println(e);
this.fileExists = false;
System.out.println("File does not exist.");
}
byte[] buffer = new byte[1024];
// Write status line
if (this.fileExists) {
System.out.println("Trying to write data");
try{
this.out.writeBytes("HTTP/1.0 " + "200 OK " + this.CRLF);
this.out.flush();
// Write Header
this.out.writeBytes("Content-type: " + getMime(this.fileName) + this.CRLF);
this.out.flush();
this.out.writeBytes(this.CRLF);
this.out.flush();
// Read file data
byte[] fileData = new byte[1024];
int i;
while ((i = this.f.read(fileData)) > 0) {
// Write File data
try{
this.out.write(fileData,0, i);
} catch (IOException e) {
System.out.println(e);
}
}
this.out.flush(); // Flush output stream
System.out.println("Flushed");
closeSock(); // Closes socket
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to send a message to a particular client e.g. client 1 wants to send a message to client 2. Client 1 sends a message to the sever, the sever computes the answer and sends it to client 2 who displays it.
I'm using a HashMap to store each client. It compiles, but when I run it, it crashed when sending the message and displays
Problem with Communication Server
I believe the error is in the loop where I'm sending the message but I can't see what's wrong with it, do I need separate code on the client side?
Server:
import java.net.*;
import java.util.*;
import java.io.*;
public class EchoServer2b extends Thread implements Runnable{
protected static Socket clientSocket;
static String [] logs = new String[100];
//protected static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
static HashMap<String, Socket> clients = new HashMap<String, Socket>();
static int arrayPos = 0;
static int i, clientCount = 0;
static String clientID;
static String receiver="",actualMessage="";
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2b (serverSocket.accept());
++clientCount;
clientID = Integer.toString(clientCount);
clients.put(clientID, clientSocket);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally{
try{
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private EchoServer2b (Socket clientSoc){
clientSocket = clientSoc;
start();
}
public void run(){
System.out.println ("New Communication Thread Started");
try{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client ID: " + clientID);
String inputLine;
while ((inputLine = in.readLine()) != null) { //reading
System.out.println(inputLine);
String message[]=inputLine.split(", ");
logs[arrayPos] = message[1]; //keep record of all commands sent to server
arrayPos++; //update array position
receiver=message[0];
actualMessage=message[1];
if (actualMessage.equals("Bye.")) //break if client enters 'Bye."
break;
if(actualMessage.equals("Logs.")){ //print out contents of logs if any client enters 'Logs'
for(i=0; i<arrayPos; i++){
System.out.println("Log"+ i + ": " + logs[i]);
}
break;
}
for (Map.Entry<String, Socket> entry: clients.entrySet()) {
String clientName = entry.getKey();
if(clientName.equals(receiver))
{
Socket socket = entry.getValue();
try {
PrintWriter receiverOut = new PrintWriter(socket.getOutputStream(), true);
//DataOutputStream receiverDOS = new DataOutputStream(socket.getOutputStream());
int x, y, result;
String num1, num2, operator;
String [] splitStrings = actualMessage.split(" ");
num1 = splitStrings[0];
x = Integer.parseInt(num1);
operator = splitStrings[1];
num2 = splitStrings[2];
y = Integer.parseInt(num2);
switch(operator){
case "+":
result = x + y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "-":
result = x - y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "*":
result = x * y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
case "/":
result = x / y;
System.out.println ("Server: " + result);
receiverOut.println(result);
break;
default:
System.out.println("Please enter a more simple equation using one of the 4 main operators i.e. '+, -, *, /'");
break;
}
receiverOut.flush();
receiverOut.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
out.flush();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e){
System.err.println("Problem with Communication Server");
e.printStackTrace();
System.exit(1);
}
}
public void sendMessage(String receiver, String actualMessage) {
}
}
Client:
import java.io.*;
import java.net.*;
public class EchoClientB {
static boolean flag = true;
public static void main(String[] args) throws IOException{
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (UnknownHostException e){
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e){
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput = "";
System.out.println ("Type Message (\"Bye.\" to quit)");
//System.out.println("Enter a simple math equation i.e. 2 + 2 separated by a space…");
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
while(true){
if(userInput.equals("Bye.")){
break;
}
if((userInput = stdIn.readLine()) != null){
out.println(userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
out.flush();
}
else if(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter the ID of the client you want to send the message to and a simple equation.");
System.out.println("Eg:2, 2 + 2 (with each element of the equation separated by a space…)");
out.flush();
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
In the server run method, at the end of the code where you are sending a message to one of the clients, you have
out.flush();
out.close();
in.close();
clientSocket.close();
}
}
catch (IOException e){
System.err.println("Problem with Communication Server");
System.exit(1);
}
This is closing the socket, and it why you are getting the exception. You may want to move this block to a place where you really do want to close the client's connection
You are getting a IOException because you're closing the stream you're trying to read from at line 140. I suggest you move all the steam closes out of while scope (line 142).
client server chat system as server start the server and client connect to the server..when client tries to connect to server, it success but the array goes to lost connection condition.
catch (Exception ex) {
outputTextArea.append("Lost a connection. \n");
ex.printStackTrace();
clientOutputStreams.remove(client);
anyway to fix it?
Server side code
public ClientHandler(Socket clientSocket, PrintWriter user) {
// new inputStreamReader and then add it to a BufferedReader
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} // end try
catch (Exception ex) {
outputTextArea.append("Error beginning StreamReader. \n");
} // end catch
} // end ClientHandler()
public void run() {
String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat" ;
String[] data;
try {
while ((message = reader.readLine()) != null) {
outputTextArea.append("Received: " + message + "\n");
data = message.split(":");
for (String token:data) {
outputTextArea.append(token + "..\n");
}
if (data[2].equals(connect)) {
tellEveryone((data[0] + ":" + data[1] + ":" + chat));
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
tellEveryone((data[0] + ":has disconnected." + ":" + chat));
userRemove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
} else {
outputTextArea.append("No Conditions were met. \n");
}
} // end while
} // end try
catch (Exception ex) {
outputTextArea.append("Lost a connection. \n");
ex.printStackTrace();
clientOutputStreams.remove(client);
} // end catch
} // end run()
public void userAdd (String data) {
String message, add = ": :Connect", done = "Server: :Done", name = data;
outputTextArea.append("Before " + name + " added. \n");
userlist.add(name);
outputTextArea.append("After " + name + " added. \n");
String[] tempList = new String[(userlist.size())];
userlist.toArray(tempList);
for (String token:tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void userRemove (String data) {
String message, add = ": :Connect", done = "Server: :Done", name = data;
userlist.remove(name);
String[] tempList = new String[(userlist.size())];
userlist.toArray(tempList);
for (String token:tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void tellEveryone(String message) {
// sends message to everyone connected to server
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
outputTextArea.setCaretPosition(outputTextArea.getDocument().getLength());
} // end try
catch (Exception ex) {
outputTextArea.append("Error telling everyone. \n");
} // end catch
} // end while
} // end tellEveryone()
errors
java.lang.ArrayIndexOutOfBoundsException: 2
at chatsystemserver.ServerSide$ClientHandler.run(ServerSide.java:55)
at java.lang.Thread.run(Thread.java:745)
any idea how to fix the data[2]?
Check if the array has at least 3 elements. That is, change
if (data[2].equals(connect)) {
to
if (data.length > 2 && data[2].equals(connect)) {
I am sending lines through a socket from a client in C, and reading on a server in Java. The best I can manage is that the client send the multiple lines, and when I close the client the server prints all the data in one line. Or to make it that one send then receives, etc. My desire is that the C application sends "Hi" in a loop, and the Java files catches first hi, prints and then catches second and prints. Right now it prints "HiHiHiHi...", but only when the connection is terminated.
I am using oracle socket example as guideline and using another guide for the C client
So reading the socket in Java is:
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connected with client");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("RECEIVING " + inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
Trying to write to the socket in a while loop the same string in C:
void connection(void) {
int sockfd, portno;
struct sockaddr_in serv_addr;
struct hostent *server;
/* Set time limit. */
timeout.tv_sec = 0;
timeout.tv_usec = 10;
portno = 4444;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("Localhost");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1) {
/* Create a descriptor set containing our two sockets. */
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
bzero(buffer,256);
char *buffer2 = "here";
n = write(sockfd,buffer2,strlen(buffer2));
if (n < 0)
error("ERROR writing to socket");
}
}
Your server is waiting for a \n before it prints anything.
Your client isn't sending any \n chars.
You might try:
char *buffer2 = "here"\n;