Here's my code I get the js ws working but when y try to send a message to the websocket :glassfish returns:
INFO: Error : SessionImpl{uri=/Formosa2/endpoint, id='b821d249-6435-45fe-812d- 577bc5fc8fca', endpoint=EndpointWrapper{endpointClass=null, endpoint=org.glassfish.tyrus.core.AnnotatedEndpoint#1602760, uri='/Formosa2/endpoint', contextPath='/Formosa2'}}
#ServerEndpoint(value = "/endpoint")
#Singleton
public class websocket {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
#OnMessage
public void onMessage(String message) {
String filteredMessage = String.format("%s: %s", message.toString());
broadcast(filteredMessage);
System.out.println(message);
}
#OnOpen
public void onOpen(Session peer){
peers.add(peer);
String message = String.format("* %s %s", "User has joined.");
broadcast(message);
}
#OnClose
public void onClose(Session peer){
peers.remove(peer);
}
#OnError
public void onError(Session aclientSession, Throwable aThrowable) {
System.out.println("Error : " + aclientSession);
}
private void broadcast(String message) {
for (Session peer : peers) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
peer.getBasicRemote().sendText(buffer.toString());
} catch (IOException ignore) {
// Ignore
}
}
}
}
and
<script type="text/javascript">
ws = new WebSocket('ws://' + window.location.host + '/Formosa2/endpoint'); //Annotation
ws.onopen = function(event) {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
sendMessage();
}
};
};
ws.onmessage = function(event) {
sendMessage(event);
};
ws.onclose = function(event) {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
ws.onerror = function(event){
alert("Error : " + event.data);
Console.log(message.data);
};
function sendMessage (event) {
var text = document.getElementById('form:texto').value;
var select = document.getElementById('form:empresaidEmpresa');
var text2 = document.getElementById('inicio_input').value;
var name = select.options[select.selectedIndex].text;
ws.send(texto +', '+ name +',' + text2);
document.getElementById('chat').value = '';
}
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
// Chat.initialize();
</script>
String message = String.format("* %s %s", "User has joined.");
this line was the problem
format modifiers were incorret,I was able to discover that by reading in the log (system.out..) of the aThrowable parameter.
Related
I'm really new in Kotlin.
I have two application one is Client in Android emulator and one is in Windows Form Application Server (My server is Using SimpleTCP library in C#) .
Here is the Server Code:
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13;
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
messageList.Text += "Server starting...";
server.Start("192.168.1.7", 5000);
messageList.Text += "\r\n Server started...";
}
private void Server_DataReceived(object sender, SimpleTCP.Message e)
{
messageList.Invoke((MethodInvoker)delegate ()
{
messageList.Text += string.Format("\r\n Client Message: {0} \n ", e.MessageString);
});
e.ReplyLine("Hello from Server");
}
I'm communicating via localhost. I can send request and Server can get this request without problem but when i try to get response from Server unfortunately cannot receive response.
val message = input!!.readLine() is always returning null
Can you help me why i cannot do this?
Here my code
var thread: Thread? = null
var etIP: EditText? = null
var etPort: EditText? = null
var tvMessages: TextView? = null
var etMessage: EditText? = null
var btnSend: Button? = null
var SERVER_IP: String? = null
var SERVER_PORT = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
etIP = findViewById(R.id.etIP)
etPort = findViewById(R.id.etPort)
tvMessages = findViewById(R.id.tvMessages)
etMessage = findViewById(R.id.etMessage)
btnSend = findViewById(R.id.btnSend)
val btnConnect: Button = findViewById(R.id.btnConnect)
btnConnect.setOnClickListener {
tvMessages!!.text = ""
SERVER_IP = etIP!!.text.toString().trim { it <= ' ' }
SERVER_PORT = etPort!!.text.toString().trim { it <= ' ' }.toInt()
thread = Thread(Thread1())
thread!!.start()
}
btnSend!!.setOnClickListener {
val message = "Android!"+etMessage!!.text.toString().trim { it <= ' ' }
if (!message.isEmpty()) {
Thread(Thread3(message)).start()
}
}
}
private var output: PrintWriter? = null
private var input: BufferedReader? = null
internal inner class Thread1 : Runnable {
override fun run() {
val socket: Socket
try {
socket = Socket(SERVER_IP, SERVER_PORT)
output = PrintWriter(socket.getOutputStream())
input = BufferedReader(InputStreamReader(socket.getInputStream()))
runOnUiThread(Runnable { tvMessages!!.text = "Connected\n" })
Thread(Thread2()).start()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
internal inner class Thread2 : Runnable {
override fun run() {
while (true) {
try {
val message = input!!.readLine().toString()
run {
runOnUiThread(Runnable { tvMessages!!.append("server: $message\n") })
}
run {
thread = Thread(Thread1())
thread!!.start()
return
}
} catch (e: Exception) {
tvMessages!!.text = e.toString()
}
}
}
}
internal inner class Thread3(private val message: String) : Runnable {
override fun run() {
output!!.write(message)
output!!.flush()
runOnUiThread(Runnable {
tvMessages!!.append("client: $message\n")
tvMessages!!.setMovementMethod(ScrollingMovementMethod())
etMessage!!.setText("")
})
}
}
fun clearAll(view: View){
tvMessages!!.text = ""
}
I am new to the HTTP request in java. I have been trying to send an HTTP Post request to my NODE.JS server with the parameter key:12345. However, it doesn't send anything to my server. I tried tested my NOEDJS server to see if it worked in POSTMAN, and it did. So I am sure that this is something with the java that I made. I think a look at my code would help. Here it is down below.
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class ConnectionFactory {
private double API_VERSION = 0;
private String API = "";
private String METHOD = "POST";
private String USER_AGENT = "Mozilla/5.0";
private String TYPE = "application/x-www-form-urlencoded";
private String data = "";
private URL connection;
private HttpURLConnection finalConnection;
private HashMap<String, String> fields = new HashMap<String, String>();
public ConnectionFactory(String[] endpoint, String url, double version) {
this.API_VERSION = version;
this.API = url;
fields.put("version", String.valueOf(version));
for (int i = 0; i < endpoint.length; i++) {
String[] points = endpoint[i].split(";");
for (int f = 0; f < points.length; f++) {
fields.put(points[f].split(":")[0], points[f].split(":")[1]);
}
}
}
public String buildConnection() {
StringBuilder content = new StringBuilder();
if (!this.getEndpoints().equalsIgnoreCase("") && !this.getEndpoints().isEmpty()) {
String vars = "";
String vals = "";
try {
for (Map.Entry<String, String> entry: fields.entrySet()) {
vars = entry.getKey();
vals = entry.getValue();
data += ("&" + vars + "=" + vals);
}
if (data.startsWith("&")) {
data = data.replaceFirst("&", "");
}
connection = new URL(API);
BufferedReader reader = new BufferedReader(new InputStreamReader(readWithAccess(connection, data)));
String line;
while ((line = reader.readLine()) != null) {
content.append(line + "\n");
}
reader.close();
return content.toString();
} catch (Exception e) {
System.err.println(e.getMessage());
}
} else {
return null;
}
return null;
}
private InputStream readWithAccess(URL url, String data) {
try {
byte[] out = data.toString().getBytes();
finalConnection = (HttpURLConnection) url.openConnection();
finalConnection.setRequestMethod(METHOD);
finalConnection.setDoOutput(true);
finalConnection.addRequestProperty("User-Agent", USER_AGENT);
finalConnection.addRequestProperty("Content-Type", TYPE);
finalConnection.connect();
try {
OutputStream os = finalConnection.getOutputStream();
os.write(out);
} catch (Exception e) {
System.err.println(e.getMessage());
}
return finalConnection.getInputStream();
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
public String getApiVersion() {
return String.valueOf(API_VERSION);
}
public String getEndpoints() {
return fields.toString();
}
public String getEndpointValue(String key) {
return fields.get(key);
}
public void setUserAgent(String userAgent) {
this.USER_AGENT = userAgent;
}
public void setMethod(String method) {
this.METHOD = method;
}
public void setSubmissionType(String type) {
this.TYPE = type;
}
}
public class example {
public static void main(String[] args) {
double version = 0.1;
String url = "http://localhost:3000";
String[] fields = {
"key:12345"
};
ConnectionFactory connection = new ConnectionFactory(fields, url, version);
connection.setUserAgent("Mozilla/5.0");
String response = connection.buildConnection();
System.out.println(response);
}
}
Here is the code for my node.js server
var http = require('http');
var url = require('url');
var queryString = require('querystring')
var StringDecoder = require('string_decoder').StringDecoder;
var server = http.createServer(function(req, res) {
//parse the URL
var parsedURL = url.parse(req.url, true);
//get the path
var path = parsedURL.pathname;
var trimmedPath = path.replace(/^\/+|\/+$/g, '');
//queryString
var queryStringObject = parsedURL.query;
console.log(queryStringObject);
if (queryStringObject.key == 12345) {
console.log("true")
res.end("true")
} else {
console.log("failed")
res.end("false")
}
// var query = queryStringObject.split()
});
server.listen(3000, function() {
console.log("Listening on port 3000");
});
The is no problem with your java client
The problem is that you are sending the content of your POST request as ""application/x-www-form-urlencoded" and then in your nodeJS server you are reading it as a query string
Here is a correct example using ExpressJS :
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/test', function(req, res) {
var key = req.body.key;
if (key==12345)
res.send(true );
else
res.send(false);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
I am trying to upload an Image on Java Server.the File is trnsfering from android device but saving null on server .
Here is server code
public UploadMediaServerResponse uploadFileForFunBoard(#FormDataParam("photoPath") InputStream photoInputStream,
#FormDataParam("photoPath") FormDataContentDisposition photoFileDetail,
#FormDataParam("userId") int userId, #FormDataParam("mediaType") String mediaType,
#FormDataParam("title") String title,#FormDataParam("funBoardId") int funBoardId)
{
MediaContenModel mediaContenModel = new MediaContenModel();
mediaContenModel.setFunBoardId(funBoardId);
mediaContenModel.setMediaType(mediaType);
mediaContenModel.setUserId(userId);
UploadMediaServerResponse uploadMediaServerResponse = new UploadMediaServerResponse();
boolean isMediaProcessedAndUploaded = true;
String mediaProcessingError = "";
if (photoInputStream != null && photoFileDetail != null)
{
uploadMediaServerResponse = mediaService.uploadOnServer(photoInputStream,
photoFileDetail.getFileName(), userId+"");
if (uploadMediaServerResponse != null
&& !uploadMediaServerResponse.getMediaUrl().equalsIgnoreCase("ERROR"))
{
mediaContenModel.setImageUrl(uploadMediaServerResponse.getMediaUrl());
logger.debug("ContentService --> createStroyline --> fearture Image url ::"
+ uploadMediaServerResponse.getMediaUrl());
}
else
{
isMediaProcessedAndUploaded = false;
mediaProcessingError = uploadMediaServerResponse.getMediaUrl();
logger.debug("ContentService --> createStroyline --> mediaProcessingError ::"
+ mediaProcessingError);
}
}
if (isMediaProcessedAndUploaded)
{
UploadMediaServerResponse response = funBoardService.uploadMediaContent(mediaContenModel);
uploadMediaServerResponse.setMediaUrl(response.getMediaUrl());
}
else
{
uploadMediaServerResponse.setError("Task Failed");
uploadMediaServerResponse.setStatus(ServiceAPIStatus.FAILED.getStatus());
}
return uploadMediaServerResponse;
}
here is my phonegap code
var pictureSource;
var destinationType;
function onPhotoURISuccess(imageURI)
{
console.log(imageURI);
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="photoPath";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.params = {
"userId": 1,
"funBoardId": 3,
"mediaType": 'image'
};
console.log(JSON.stringify(options));
var ft = new FileTransfer();
ft.upload(imageURI, _BaseURL+"mobile/userService/funboard/upload", win, fail, options);
}
function onPhotoDataSuccess(imageURI)
{
var imgProfile = document.getElementById('imgProfile');
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1)
{
getLocation();
}
movePic(imageURI);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function movePic(file)
{
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
function resolveOnSuccess(entry)
{
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys)
{
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory)
{
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
function successMove(entry)
{
alert(entry.fullPath);
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error)
{
alert(error.code);
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
04-14 19:33:46.010: E/FileTransfer(13550): java.io.FileNotFoundException: http:///jeeyoh/mobile/userService/funboard/upload
Thanks in Advance
Replace
options.fileKey="file";
To
options.fileKey="photoPath";
i am devloping a group chat appication and i want to send username and password at the time of handshaking.
Here is my client side javascript code:
<script type="text/javascript">
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
alert("'Error: WebSocket is not supported by this browser.'")
Console.log('Error: WebSocket is not supported by this browser.');
return;
}
Chat.socket.onopen = function() {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function() {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
Chat.socket.onmessage = function(message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host
+ '/WebSocketDemo/ChatWebSocketServlet');
} else {
Chat.connect('wss://' + window.location.host
+ '/WebSocketDemo/ChatWebSocketServlet');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
</script>
and i have used tomcat 7 as a server.
Here is my server side code:
#Deprecated
public class ChatWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private static final String GUEST_PREFIX = "Guest";
private final AtomicInteger connectionIds = new AtomicInteger(0);
private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>();
#Override
protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest request) {
return new ChatMessageInbound(connectionIds.incrementAndGet());
}
private final class ChatMessageInbound extends MessageInbound {
private final String nickname;
private ChatMessageInbound(int id) {
System.out.println("stage 1");
this.nickname = GUEST_PREFIX + id;
}
#Override
protected void onOpen(WsOutbound outbound) {
connections.add(this);
System.out.println("user:" + this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#Override
protected void onClose(int status) {
connections.remove(this);
String message = String.format("* %s %s", nickname,
"has disconnected.");
broadcast(message);
}
#Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
throw new UnsupportedOperationException(
"Binary message not supported.");
}
#Override
protected void onTextMessage(CharBuffer message) throws IOException {
// Never trust the client
String filteredMessage = String.format("%s: %s", nickname,
HTMLFilter.filter(message.toString()));
broadcast(filteredMessage);
}
private void broadcast(String message) {
for (ChatMessageInbound connection : connections) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
connection.getWsOutbound().writeTextMessage(buffer);
} catch (IOException ignore) {
// Ignore
}
}
}
}
}
Here i want to send User's credential before actual handshaking to authenticate user.
so how i can to in this?
I currently have a java backend running on my server and I have come across a script to communicate from Java to Node.js. I am wondering how I can modify the script to allow more then one message at a time, and if possible, use it in reverse to communicate back to Java.
Here is the code:
Java Side:
package com.timetablr.backend.nodecommunicator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class NodeCommunicator {
public static void main(String[] args) {
try {
Socket nodejs = new Socket("localhost", 8080);
sendMessage(nodejs, "testnamespace");
Thread.sleep(100);
int x = 0;
while (true)
{
sendMessage(nodejs, x + "");
x++;
Thread.sleep(1000);
System.out.println(x + " has been sent to server");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendMessage(Socket s, String message) throws IOException {
s.getOutputStream().write(message.getBytes("UTF-8"));
s.getOutputStream().flush();
}
public static String readMessage(Socket s) throws IOException {
InputStream is = s.getInputStream();
int curr = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((curr = is.read()) != -1) {
if (curr == '\n') {
break;
}
baos.write(curr);
}
return baos.toString("UTF-8");
}
}
Node.js Side:
var javaPort = 8080;
var sIOPort = 8081;
var javaServer = require('net').createServer();
var browserServer = require('socket.io').listen(sIOPort);
console.log('=====================================================');
console.log('JamesS237 Timetablr Node.js/Java Communication Module');
console.log('=====================================================');
console.log('Socket.IO version: ' + require('socket.io').version);
javaServer.on('listening', function () {
console.log('Server is listening on ' + javaPort);
});
javaServer.on('error', function (e) {
console.log('Server error: ' + e.code);
});
javaServer.on('close', function () {
console.log('Server closed');
});
javaServer.on('connection', function (javaSocket) {
var clientAddress = javaSocket.address().address + ':' + javaSocket.address().port;
console.log('Java ' + clientAddress + ' connected');
var firstDataListenner = function (data) {
console.log('Received namespace from java: ' + data);
console.log(data);
javaSocket.removeListener('data', firstDataListenner);
createNamespace(data, javaSocket);
}
javaSocket.on('data', firstDataListenner);
javaSocket.on('close', function() {
console.log('Java ' + clientAddress + ' disconnected');
});
});
javaServer.listen(javaPort);
function createNamespace(namespaceName, javaSocket) {
var browserConnectionListenner = function (browserSocket) {
console.log('Browser Connected');
var javaSocketDataListenner = function(data) {
console.log('Data received from java socket and sent to browser: ' + data);
browserSocket.emit('m', data + '\r\n');
}
var javaSocketClosedListenner = function() {
console.log('The java socket that was providing data has been closed, removing namespace');
browserSocket.disconnect();
browserServer.of('/' + namespaceName).removeListener('connection', browserConnectionListenner);
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
}
javaSocket.on('close', javaSocketClosedListenner);
javaSocket.on('data', javaSocketDataListenner);
browserSocket.on('disconnect', function () {
console.log('Browser Disconnected');
javaSocket.removeListener('data', javaSocketDataListenner);
javaSocket.removeListener('close', javaSocketClosedListenner);
});
}
var namespace = browserServer.of('/' + namespaceName).on('connection', browserConnectionListenner);
}
Thanks in advance, this is a tricky one