Tag Not defined for MsgType 110 - quickfix

I am trying to get the security list response from the Fix Server using QuickFix4J, but I am getting following error :
<20230201-05:21:05, FIX.4.4:targetId->senderId, error> (Reject sent for message 2: Tag not defined for this message type, field=110)
Here's my request :
private void getSecurityList(SessionID sessionID){
String id = UUID.randomUUID().toString();
System.out.println("Sending security list request : >>>>>>>>>>> ");
SecurityListRequest request = new SecurityListRequest();
request.getHeader().setField(new MsgType(MsgType.SECURITY_LIST_REQUEST));
request.getHeader().setField(new SenderCompID(senderId));
request.getHeader().setField(new TargetCompID(targetCompanyId));
request.set(new SecurityReqID(id));
request.set(new SecurityListRequestType(SecurityListRequestType.ALL_SECURITIES));
try {
Session.sendToTarget(request);
} catch (SessionNotFound e) {
throw new RuntimeException(e);
}
}
here's my FIX config :
[default]
FileStorePath=target/data/company
ConnectionType=initiator
SenderCompID=senderId
TargetCompID=targetId
SocketConnectHost=someurl.com
StartTime=00:00:00
EndTime=00:00:00
HeartBtInt=30
ReconnectInterval=60
FileLogPath=logs-client
ResetOnLogon=Y
ForceResync=Y
[session]
BeginString=FIX.4.4
SocketConnectPort=62481
LogonTag=553=something
LogonTag1=554=something
Here's how I handle the response :
#EventListener
public void handleFromApp(FromApp fromApp) throws FieldNotFound {
System.out.println("From App : ");
Message message = (Message) fromApp.getMessage();
System.out.println("From App Message Type : " + message.getHeader().getString(MsgType.FIELD));
// SessionID sessionID = fromApp.getSessionId();
if (message instanceof MarketDataSnapshotFullRefresh){
MarketDataSnapshotFullRefresh marketData = (MarketDataSnapshotFullRefresh) message;
orderBookService.getOrderBookFromFix(marketData);
}
if (message instanceof ExecutionReport){
ExecutionReport executionReport = (ExecutionReport) message;
newOrderService.handleOrderStatus(executionReport);
}
try {
String msgType = message.getHeader().getString(MsgType.FIELD);
System.out.println("Message Type : " + msgType);
if (MsgType.SECURITY_LIST.equals(msgType)){
System.out.println("Received security list response >>>> mapping now >>>>>>>> ");
securityListResponseMapper(message);
}
} catch (FieldNotFound e) {
throw new RuntimeException(e);
}
}
Response that I am logging before my client rejects it :
(8=FIX.4.4#9=2153#35=y#49=senderId#56=targetId#34=2#52=20230201-05:06:22.877#320=9b578bc4-9d00-4a3b-898d-3d649bf52612#322=111#560=0#146=60#55=ETH/USD_CFD#110=0.00000001#1208=0.01#55=BTC/USD_CFD#110=0.0001#1208=0.01#55=LTC/BTC#110=0.0001#1208=0.000001#55=WAXP/USC#110=0.000001#1208=0.000001#55=ETH/BTC#110=0.0001#1208=0.000001#55=TUSD/USC#110=0.01#1208=0.00001#55=LTC/USD_CFD#110=0.00000001#1208=0.01#55=DOGE/USC#110=0.1#1208=0.0001#55=LTC/USC#110=0.0001#1208=0.01#55=BCH/USC#110=0.0001#1208=0.01#55=XRP/JPY_CFD#110=1#1208=0.001#55=XRP/JPY#110=1#1208=0.001#55=XRP/USD_CFD#110=0.1#1208=0.0001#55=LTC/JPY_CFD#110=0.00000001#1208=1#55=LTC/JPY#110=0.00000001#1208=1#55=BCH/JPY#110=0.00000001#1208=1#55=BCH/USD_CFD#110=0.00000001#1208=0.01#55=ETH/JPY_CFD#110=0.00000001#1208=1#55=ETH/JPY#110=0.00000001#1208=1#55=DASH/USDC#110=0.00001#1208=0.01#55=ETH/USDC#110=0.01#1208=0.01#55=LTC/USD#110=0.00000001#1208=0.01#55=BCH/USDC#110=0.0001#1208=0.01#55=BCH/JPY_CFD#110=0.00000001#1208=1#55=ETH/USD#110=0.00000001#1208=0.01#55=DASH/USD#110=0.00001#1208=0.01#55=PAX/USDC#110=0.01#1208=0.00001#55=PAXG/USDC#110=0.01#1208=0.00001#55=XRP/USDC#110=0.0001#1208=0.01#55=DOGE/USDC#110=0.1#1208=0.0001#55=BTC/UST#110=0.01#1208=0.01#55=TUSD/USDC#110=0.01#1208=0.00001#55=BCH/UST#110=0.01#1208=0.01#55=WAXP/USD#110=0.000001#1208=0.000001#55=DASH/USDT#110=0.00001#1208=0.01#55=USDT/USD#110=0.01#1208=0.00001#55=PAXG/USC#110=0.01#1208=0.00001#55=XRP/USDT#110=100#1208=0.00001#55=LTC/USDC#110=0.0001#1208=0.01#55=USDC/USD#110=0.01#1208=0.01#55=DOGE/USDT#110=0.1#1208=0.0001#55=ALGO/USD#110=0.1#1208=0.0001#55=BTC/USD#110=0.00000001#1208=0.01#55=BTC/JPY#110=0.00000001#1208=1#55=LTC/UST#110=0.01#1208=0.01#55=DOGE/USD#110=0.1#1208=0.0001#55=BTC/USDT#110=0.01#1208=0.01#55=BTC/USDC#110=0.00001#1208=0.01#55=BCH/USD#110=0.00000001#1208=0.01#55=ETH/USDT#110=0.01#1208=0.01#55=ETH/UST#110=0.01#1208=0.01#55=BCH/USDT#110=0.01#1208=0.01#55=PAX/USC#110=0.01#1208=0.00001#55=DASH/USC#110=0.00001#1208=0.01#55=BTC/USC#110=0.00001#1208=0.01#55=XRP/UST#110=100#1208=0.00001#55=LTC/USDT#110=0.01#1208=0.01#55=ETH/USC#110=0.01#1208=0.01#55=XRP/USC#110=0.0001#1208=0.01#55=BTC/JPY_CFD#110=0.00000001#1208=1#10=249#)
Image of PDF doc, how the response is structured from the broker.

Related

Netty connection pool not sending messages to server

I have a simple netty connection pool and a simple HTTP endpoint to use that pool to send TCP messages to ServerSocket. The relevant code looks like this, the client (NettyConnectionPoolClientApplication) is:
#SpringBootApplication
#RestController
public class NettyConnectionPoolClientApplication {
private SimpleChannelPool simpleChannelPool;
public static void main(String[] args) {
SpringApplication.run(NettyConnectionPoolClientApplication.class, args);
}
#PostConstruct
public void setup() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.remoteAddress(new InetSocketAddress("localhost", 9000));
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new DummyClientHandler());
}
});
simpleChannelPool = new SimpleChannelPool(bootstrap, new DummyChannelPoolHandler());
}
#RequestMapping("/test/{msg}")
public void test(#PathVariable String msg) throws Exception {
Future<Channel> future = simpleChannelPool.acquire();
future.addListener((FutureListener<Channel>) f -> {
if (f.isSuccess()) {
System.out.println("Connected");
Channel ch = f.getNow();
ch.writeAndFlush(msg + System.lineSeparator());
// Release back to pool
simpleChannelPool.release(ch);
} else {
System.out.println("not successful");
}
});
}
}
and the Server (ServerSocketRunner)
public class ServerSocketRunner {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
System.out.println("New client connected");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));) {
String inputLine, outputLine;
out.println("Hello client!");
do {
inputLine = in.readLine();
System.out.println("Received: " + inputLine);
} while (!"bye".equals(inputLine));
System.out.println("Closing connection...");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
DummyChannelPoolHandler and DummyClientHandler just print out events that happen, so they are not relevant. When the server and the client are started and I send a test message to test endpoint, I can see the server prints "New client connected" but the message sent by client is not printed. None of the consecutive messages sent by client are printed by the server.
If I try telnet, everything works fine, the server prints out messages. Also it works fine with regular netty client with same bootstrap config and without connection pool (SimpleNettyClientApplication).
Can anyone see what is wrong with my connection pool, I'm out of ideas
Netty versioin: 4.1.39.Final
All the code is available here.
UPDATE
Following Norman Maurer advice. I added
ChannelFuture channelFuture = ch
.writeAndFlush(msg + System.lineSeparator());
channelFuture.addListener(writeFuture -> {
System.out
.println("isSuccess(): " + channelFuture.isSuccess() + " : " + channelFuture.cause());
});
This prints out
isSuccess: false : java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion)
To fix it, I just converted String into ByteBuf
ch.writeAndFlush(Unpooled.wrappedBuffer((msg + System.lineSeparator()).getBytes()));
You should check what the status of the ChannelFuture is that is returned by writeAndFlush(...). I suspect it is failed.

FIX:How to send ,messages using FIX ,quickfixj

# Here is my settings.cfg file:
# Thank you.Here is what i tried.My settings.cfg file
[DEFAULT]
# Settings which apply to all the Sessions.
ConnectionType=initiator
LogonTimeout=30
ReconnectInterval=20
ResetOnLogon=Y
FileLogPath=C:\Work\QuickFIXJ\logs
FileStorePath=C:\Work\QuickFIXJ\logs
[SESSION]
# Settings specifically for one session
BeginString=FIX.4.4
SenderCompID=XYZ
TargetCompID=TYZ
TimeZone=Asia/Tokyo
StartTime=16:00:00
EndTime=13:30:00
HeartBtInt=60
SocketConnectPort=7200
SocketConnectHost=123.123.123.123
UseDataDictionary=Y
DataDictionary=C:\Work\QuickFIXJ\datadictionary\FIX44.xml
[GATEWAY]
Port=4444
[TRANSPORT]
Port=4444
and then
//initiator code:
public class TestQuickFixJConnectivity {
public static void main(String[] args) {
SocketInitiator socketInitiator = null;
try {
SessionSettings sessionSettings = new SessionSettings("C:\\Work\\QuickFixJ\\sessionSettings.txt");
Application application = new TestApplicationImpl();
FileStoreFactory fileStoreFactory = new FileStoreFactory(sessionSettings);
FileLogFactory logFactory = new FileLogFactory(sessionSettings);
MessageFactory messageFactory = new DefaultMessageFactory();
socketInitiator = new SocketInitiator(application,
fileStoreFactory, sessionSettings, logFactory,
messageFactory);
socketInitiator.start();
SessionID sessionId = socketInitiator.getSessions().get(0);
sendLogonRequest(sessionId);
int i = 0;
do {
try {
Thread.sleep(1000);
System.out.println(socketInitiator.isLoggedOn());
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
} while ((!socketInitiator.isLoggedOn()) && (i < 30));
} catch (ConfigError e) {
e.printStackTrace();
} catch (SessionNotFound e) {
e.printStackTrace();
} catch (Exception exp) {
exp.printStackTrace();
} finally {
if (socketInitiator != null) {
socketInitiator.stop(true);
}
}
}
private static void sendLogonRequest(SessionID sessionId) throws SessionNotFound {
Logon logon = new Logon();
Message msg=new Message();
Header header = msg.getHeader();
logon.set(new HeartBtInt(60));
logon.set(new ResetSeqNumFlag(true));
header.setField(new BeginString("FIX.4.4"));
header.setField(new MsgType("AP"));
header.setField(new SenderCompId("XYZ"));
header.setField(new TagetCompId("TYZ"));
header.setField(new ResetSeqNumFlag(true));
//here i m setting all the fields in the csv report .
msg.setField(705,new SortQty(""));
// ....
//below statement returning false
boolean sent = Session.sendToTarget(msg, sessionId);
System.out.println("Logon Message Sent : " + sent);
}
}
Please find my observations below:
In the event logs I am seeing as Created session: and the message which I am trying to send. Also I could see that the sender sequence number is getting incremented in the logs.
Messages.log and header.logs are blank and body.log has the message which i am trying to send.
Also onCreate and ToApp are being called when I try to run the code.
I want to know whether i have sent the message successfully ?
Also boolean sent = Session.sendToTarget(msg, sessionId); is returning false.
I don't see ToAdmin and FromAdmin being executed in my code. Also Do I need to write the acceptor code as well for the same, or just the initiator code will be fine. The DataDictionary which i am using has all the fields set, but I am not sure whether its being used by QuickFixJ when i try to execute the code.
Please advise whats going wrong in this?
OK your settings file looks ok and you're saying it works, but I don't think you need GATEWAY and TRANSPORT headings
As for your code, all you need to do to start with is setup the default QuickFIX Application, FileStoreFactory, LogFactory, MessageFactory and Initiator which you have done.
The default QuickFIX automatically logs on to the Target in your settings file, and if the logon is accepted then it begins to heartbeat. From your comments it sounds like this is happening.
So what's going wrong is your sendLogonRequest is not necessary. Also, if you do send "extra" logons then the target FIX engine will probably reject or ignore them. The reject message would be seen in the logs or file store.
So then you have the QuickFIX API with which to start with you can simply output messages to your own log.
Something like this
public void fromApp(Message msg, SessionID s) throws UnsupportedMessageType, FieldNotFound, IncorrectTagValue
{
log.debug(String.valueOf(LocalTime.now()) + " INITIATOR: FromApp " + msg.toString());
}
public void toApp(Message msg, SessionID s)
{
log.info(String.valueOf(LocalTime.now()) + " INITIATOR: ToApp " + msg.toString());
}
public void fromAdmin(Message msg, SessionID s) throws FieldNotFound, IncorrectTagValue
{
Log.trace("INITIATOR: FromAdmin " + msg.getClass() + " " + msg.toString());
}
public void onCreate(SessionID s)
{
log.info("INITIATOR: OnCreate " + s.toString());
}
public void onLogout(SessionID s)
{
log.error("INITIATOR: OnLogout " + s.toString());
}
public void onLogon(SessionID s)
{
log.info("INITIATOR: OnLogon " + s.toString());
}
public void toAdmin(Message msg, SessionID s)
{
log.trace("INITIATOR: ToAdmin " + msg.getClass() + " " + msg.toString());
}
Then when you want to send a message, try something like this:
QuoteReqID id = new QuoteReqID("1234");
// Create Quote Request message
QuoteRequest qr = new QuoteRequest(id);
// Setup outgoing group and specify an index for each group tag
NoRelatedSym g = new NoRelatedSym();
String instrument = m.getString("EUR/USD");
Symbol symbol = new Symbol(instrument);
g.setField(1, symbol);
QuoteRequestType qt = new QuoteRequestType(102);
g.setField(2, qt);
OrderQty qty = new OrderQty("1000000");
g.setField(3, qty);
SettlType sType = new SettlType("B");
g.setField(4, sType);
SettlDate sDate = new SettlDate("20170315");
g.setField(5, sDate);
Account account = new Account("357647");
g.setField(6, account);
// add group to request
qr.addGroup(g);
Session s = Session.lookupSession(i.getSessions().get(0));
s.send(qr);

Jetty Java websocket client doesn't connect to server

I am using Java Jetty client written [websocket-client 9.3.8.RC0]. Websocket server is little wierd in our case.
It accepting request in format.
wss://192.168.122.1:8443/status?-xsrf-=tokenValue
Token Value is received in first Login POST request in which i get Token Value & Cookie header. Cookie is added as a header whereas token is given as a param.
Now question is : -
When i run below code it just call awaitclose() function in starting. But there is not other function called i.e. Onconnected or even Onclose.
Any help would be appreciated to debug it further, to see any logs or environment issue to see why Socket is not connected.
Trying to figure out following points to debug.
1. To check if client certificates are causing issue.
Tried with my python code wspy.py it work seemlessly fine.
Code is
public final class websocketxxx {
WebSocketClient client=null;
public websocketxxx (){
}
public void run(String host,String cookieVal, String xsrfVal, String resource) throws IOException {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient client = new WebSocketClient(sslContextFactory);
MyWebSocket socket = new MyWebSocket();
try {
client.start();
ClientUpgradeRequest request = new ClientUpgradeRequest();
// Add the authentication and protocol to the request header
// Crate wss URI from host and resource
resource = resource + xsrfVal;
URI destinationUri = new URI("wss://" + host + resource); // set URI
request.setHeader("cookie",cookieVal);
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
//System.out.println("Request Headers print : " request.getHeaders())
System.out.println("Connecting to : " + destinationUri);
client.connect(socket, destinationUri, request);
socket.awaitClose(5000, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#WebSocket
public class MyWebSocket {
private final CountDownLatch closeLatch = new CountDownLatch(1);
#OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("WebSocket Opened in client side");
try {
System.out.println("Sending message: Hi server");
session.getRemote().sendString("Hi Server");
} catch (IOException e) {
e.printStackTrace();
}
}
#OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message from Server: " + message);
}
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("WebSocket Closed. Code:" + statusCode);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
}
public Client getBypassCertVerificationClient() {
Client client1 = null;
try {
// Create a HostnameVerifier that overrides the verify method to accept all hosts
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String host, SSLSession sslSession) {
return true;
}
};
// Create a TrustManager
TrustManager[] trust_mgr = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t) {
}
public void checkServerTrusted(X509Certificate[] certs, String t) {
}
}
};
// Create the SSL Context
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trust_mgr, new SecureRandom());
// Create the client with the new hostname verifier and SSL context
client1 = ClientBuilder.newBuilder()
.sslContext(sslContext)
.hostnameVerifier(hostnameVerifier)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return client1;
}
public String[] simple_Login_POST_request(String host, String user, String password, String resource, String data) {
String resp = null;
String[] headers = new String[2];
try {
// Create a Client instance that supports self-signed SSL certificates
Client client = getBypassCertVerificationClient();
// Create a WebTarget instance with host and resource
WebTarget target = client.target("https://" + host).path(resource);
// Build HTTP request invocation
Invocation.Builder invocationBuilder = target.request();
// Encode the user/password and add it to the request header
invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
Form form = new Form();
form.param("userid", user);
form.param("password", password);
// Invoke POST request and get response as String
//post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Response response = invocationBuilder.method("POST", Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
resp = (String) response.readEntity(String.class);
// Print input URL, input data, response code and response
System.out.println("URL: [POST] " + target.getUri().toString());
System.out.println("HTTP Status: " + response.getStatus());
System.out.println("HTTP Status: " + response.getHeaders());
headers[0] = response.getHeaderString("Set-Cookie");
//response.getStringHeaders()
headers[1] = response.getHeaderString("X-XSRF-TOKEN");
System.out.println("Response: \n" + resp);
response.close();
} catch (Exception e) {
e.printStackTrace();
}
return headers;
}
public static void main(String[] args) throws IOException {
String host = "";
String user = "";
String password = "";
String resource = "";
host ="192.168.122.1:8443";
user = "ADMIN";
password ="ADMIN";
websocketXXX wsNotification = new websocketxxx();
/////////////////////////////////////////////////////////////////
// Simple POST LOGIN Request
resource = "/api/login";
String headers[]= wsNotification.simple_Login_POST_request(host, user, password, resource, null);
////////////////////////////////////////////////////////////////
headers[0] = headers[0].substring(headers[0].lastIndexOf(",") + 1);
System.out.println("headers[0]: " + headers[0] + "\n");
String cookie = headers[0];
String XSRFToken = headers[1];
resource = "/status?-xsrf-=";
//wsNotification.simple_websocket_example(host, cookie, XSRFToken, resource);
wsNotification.run(host, cookie, XSRFToken, resource);
}
}
The implementation is mostly correct.
Setting raw Cookie and Sec-WebSocket-* headers is forbidden, you have to use the API.
Cookie handling from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("cookie",cookieVal);
To ClientUpgradeRequest.setCookies() :
ClientUpgradeRequest request = new ClientUpgradeRequest();
List<HttpCookie> cookies = new ArrayList<>();
cookies.add(new HttpCookie(...));
request.setCookies(cookies);
Note: if you are using the java CookieStore, then you can pass the CookieStore instance to the client as well, using the setCookiesFrom(CookieStore) method.
Sub Protocol Selection from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
To ClientUpgradeRequest.setSubProtocols():
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setSubProtocols("ao-json");

Xmpp Smack Chat not able to send and receiving message

I have tried to establish chat connection between two users using xmpp and OpenFire. But i am not able to send and receive message. I have pasted my code below for reference. Any help will be very helpful.
I established a connection with Smack by
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setUsernameAndPassword("admin", "admin");
config.setServiceName("172.21.4.199");
config.setHost("172.21.4.199");
config.setPort(5222);
config.setDebuggerEnabled(true);
config.setConnectTimeout(50000);
XMPPTCPConnection connection = new XMPPTCPConnection(config.build());
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
try {
connection.setPacketReplyTimeout(50000);
connection.connect();
Log.d(TAG, "SetupDefaults -- Connected");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "SetupDefaults -- Connection failed exc: "+e);
}
and its gets succesfully connected. And i try to send a chat by using
ChatManager chatManager = ChatManager.getInstanceFor(connection);
Chat chat = chatManager.createChat("user2#server.local", new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
System.out.println("processMessage -- Sent message: " + message);
}
});
try {
chat.sendMessage("Hai.. Lets we chat!");
}catch (Exception e){
Log.d(TAG, "sendChat Exc: "+e.toString());
}
But i couldn't find that processMessage gets triggered. Because that S.O.P doesn't gets triggered. But i gets
SMACK: SENT (0): Hai.. Lets we chat!
SMACK: RECV (0): Hai.. Lets we chat!
in my console while sending a chat.
Simillarly i use,
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Message message = (Message)packet;
String from = message.getFrom();
String body = message.getBody();
System.out.println("Message from: " + from + " " + body);
}
};
connection.addPacketListener(packetListener, filter);
to receive the chat. But processPacket also doesn't gets triggered.
PacketListner it's something much more general to handle stanzas, it's not what you really need. You just need a ChatMessageListner
ChatManager chatManager;
chatManager = ChatManager.getInstanceFor(connection);
chatManager.addChatListener(
**new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
{
chat.addMessageListener(new IncomingMessageListener());;
}
}
})**;
Basic implementation:
class IncomingMessageListener implements ChatMessageListener {
#Override
public void processMessage(Chat arg0, Message message) {
String from = message.getFrom();
String body = message.getBody();
if (body != null)
{
System.out.println(String.format("============ Received message '%1$s' from %2$s\n============", body, from));
guiUpdate.displayMessage(body); /* custom method */
}
else
{
System.out.println("SYSTEM: ping");
}
}

Why I am receiving null in my output?

I want to send a message to my computer from my phone using TCP..My computer is the server and my phone is the client. I am able to send a message from my phone to my computer but in the output, I get null characters ..
I paste my codes below;;
Client ::
public void startApp() {
try {
// establish a socket connection with remote server
streamConnection =
(StreamConnection) Connector.open(connectString);
// create DataOuputStream on top of the socket connection
outputStream = streamConnection.openOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
// send the HTTP request
dataOutputStream.writeChars("Hello");
dataOutputStream.flush();
// create DataInputStream on top of the socket connection
inputStream = streamConnection.openInputStream();
dataInputStream = new DataInputStream(inputStream);
// retrieve the contents of the requested page from Web server
String test="";
int inputChar;
System.out.println("Entering read...........");
while ( (inputChar = dataInputStream.read()) != -1) {
// test=test+((char)inputShar);
results.append((char) inputChar);
}
System.out.println("Leaving read...........");
// display the page contents on the phone screen
//System.out.println(" Result are "+results.toString());
System.out.println(" ");
resultField = new StringItem(null, results.toString());
System.out.println("Client says "+resultField);
resultScreen.append(resultField);
myDisplay.setCurrent(resultScreen);
} catch (IOException e) {
System.err.println("Exception caught:" + e);
} finally {
// free up I/O streams and close the socket connection
try {
if (dataInputStream != null)
dataInputStream.close();
} catch (Exception ignored) {}
try {
if (dataOutputStream != null)
dataOutputStream.close();
} catch (Exception ignored) {}
try {
if (outputStream != null)
outputStream.close();
} catch (Exception ignored) {}
try {
if (inputStream != null)
inputStream.close();
} catch (Exception ignored) {}
try {
if (streamConnection != null)
streamConnection.close();
} catch (Exception ignored) {}
}
}
My server :
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
ServerSocket sck=new ServerSocket(880);
Socket client=sck.accept();
InputStream inp= client.getInputStream();
int i;
OutputStream out=client.getOutputStream();
out.write("Testing ".getBytes());
System.out.println("Server has responded ");
String str="";
while((i=inp.read())!=-1){
str=str+((char) i);
System.out.println("USer says "+ str);
}
}
catch(Exception e){
System.out.println("Error "+e);
}
}
}
My output for the server ;;
Server has responded
USer says null H
User says null H null
User says null H null e
etc etc
I am not supposed to get this null character,why I am getting it??
Another thing, my server is writing to the stream but the client is not able to receive that,why is that?Do I need to use a separate thread for that?
Thanks in adv
I would guess that isn't your real code, and that your real code initialized str to null.