UDP connection between Lua server and Java client - java

I'm working with a UDP Client (written in Java) and a Server (written in Lua). I'm using Lua Socket for the server and DatagramSockets for the client. Connection gets established successfully. The problem is when Lua server sends a string to the Java client, Java receive() function does not get the data and blocks. pls help me.
Lua server code:
-- Server
local socket = require("socket")
host = host or "*"
port = port or 8080
s = assert(socket.bind(host, port))
c = assert(s:accept())
data = "hello"
while true
do
assert(c:send(data .. "\n"))
socket.sleep(1)
-- return 0;
end
Java client code :
import java.net.*;
import java.io.*;
public class Clientnew
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = null;
byte[] Message = new byte[100];
try {
InetAddress IP = InetAddress.getLocalHost();
Socket client = new Socket(IP, 8080);
ds = new DatagramSocket(8080);
DatagramPacket dp = new DatagramPacket(Message, 1);
ds.receive(dp);
System.out.println("Recv\n");
String str = new String(dp.getData());
System.out.println(str);
} catch (Exception e)
{
} finally
{
if (ds != null)
{
ds.close();
}
}
}
}
Both program run on the Linux Platform.

Your Lua code is a TCP Server, not a UDP one. Also, remember that UDP is connectionless...
http://w3.impa.br/~diego/software/luasocket/udp.html
You can use standard tools like netstat to check things like this.

Related

Java client in socket

I have been looking for so long for a way to connect to a server created in Python using java.
Can anyone show me how to connect with java and how to send string? It is recommended that it also works on Android
My server in python:
import socket, time
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("160.07.08.49", 6784))
soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()
while True:
print(client.recv(1024))
time.sleep(0.5)
My client in Java:
try {
Socket socket = new Socket("160.07.08.49", 6784);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write("Hello from java");
printWriter.flush();
printWriter.close();
}catch (Exception e) {e.printStackTrace();}
And I got an error from python when the Java client connected
print(soc.recv(20))
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Python echo server:
import socket
HOST = 'localhost'
PORT = 6784
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Java client:
import java.io.*;
import java.net.Socket;
public class JavaClient {
public static void main(String [] args) {
String serverName = "localhost";
int port = 6784;
try {
Socket client = new Socket(serverName, port);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The big difference is that I'm doing localhost to localhost. If you need to have the Python server available from outside of localhost, change the bind line to:
soc.bind(("0.0.0.0", 6784))
so that the server will listen on all available interfaces. Then have your Java client connect to the external IP of your server.

multithreaded client and server in distributed system (Java)

Am new to Socket programming am trying to establish a communication between a Server and a client but i don't know how to do that am a bit confused on how to go about it. I have written the program below but it is given error and i can't get my head round why.
package server;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Server {
public static void main(String[] args) {
// TODO code application logic here
try {
DatagramSocket socket = new DatagramSocket(7000);
socket.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
String message = new String (buffer);
System.out.println(message);
String Reply ="Am here";
DatagramPacket data = new DatagramPacket(Reply.getBytes(), Reply.getBytes().length, packet.getAddress(), packet.getPort());
socket.send(data);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
Client
package client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) {
// TODO code application logic here
try{
String message = "Hello Server";
String host = "localhost";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 7000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
DatagramSocket sockets = new DatagramSocket(7000);
sockets.setSoTimeout(0);
while(true)
{
byte []buffer = new byte[1024];
DatagramPacket packets = new DatagramPacket(buffer,buffer.length);
sockets.receive(packets);
String messages = new String (buffer);
System.out.println(messages);
}
}
catch (Exception error){
error.printStackTrace();
}
}
}
How can i get them communicated. I have heard about Multi-threading but can't get my head round how it works.
I get the following error.
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagramSocketImpl.java:84)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:93)
at java.net.DatagramSocket.bind(DatagramSocket.java:392)
at java.net.DatagramSocket.<init>(DatagramSocket.java:242)
at java.net.DatagramSocket.<init>(DatagramSocket.java:299)
at java.net.DatagramSocket.<init>(DatagramSocket.java:271)
at client.Client.main(Client.java:32)
If you wanting to send/receive from a client to a server using a socket then use ServerSocket on the serverside.
Then use accept - This listens for a connection to be made to this socket and accepts it.
The Socket object returned by Accept has Input and Output Stream which can be be read and written to.
The client will just use a Socket Object
See http://cs.lmu.edu/~ray/notes/javanetexamples/ for an example
If for some reason you insist on using DatagramSocket, then see this example https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
The error occurs because the port you are trying to bind your socket to is already in use. Port 7000 is used both by the client and server:
DatagramSocket sockets = new DatagramSocket(7000);

Running server and clients on one machine (netbeans 8.1)

I have a problem to run a server and clients in one (mac) machine. I can run the server but when I run the client it give me an error java.net.BindException: Address already in use
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
as far as I know that there is somthing call ssh that need to be used but I don't know how to use it to do solve this.
Thanks
public class WRRCourseWork {
public static void main(String[] args) {
try {
DatagramSocket IN_socket = new DatagramSocket(3000);
DatagramSocket OUT_socket = new DatagramSocket(5000);
IN_socket.setSoTimeout(0);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
//recive the message
IN_socket.receive(packet);
String message = new String(buffer);
System.out.println("Got message: " + message.trim());
// send the message
String host = "";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket OUT_Packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 5000);
OUT_socket.send(OUT_Packet);
System.out.println("Sending Message: "+ message.trim());
}
} catch (Exception error) {
error.printStackTrace();
}
}
...
public class Messages {
public static void main(String [] args) {
System.out.println("hiiiiiii");
//String host = "localhost";
try {
while (true) {
InetAddress addr = InetAddress.getLocalHost();
String message = "Hello World";
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 4000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
//socket.close();
}
} catch(Exception error) {
// catch all errors
error.printStackTrace();
}
}
}
There are a few things that you might want to change here:
1) You are sending a UDP packet on port 4000 from your client but listening on port 3000 in your server(receiver) code. Ports should be same.
2) There might be another instance of your server code running in another Netbeans tab or from your terminal may be, which is already bound to the port. Please ensure that you have only one instance running for your server code. This will resolve your 'Address already in use error'
3) I also added 'Thread.sleep(500)' in the client(sender) code in the infinite while loop that you have set up. Without this, the code was ending up with a 'Bad File Descriptor' error on my machine. Probably it was a conflict with the Socket handle running into a problem with the infinite loop in place.
With these changes, data exchange between client and server is working fine.

PHP to Java - Sockets

I am trying to communicate from php to java using sockets. I have the following java code:
private static ServerSocket socket;
private static Socket connection;
private static String command = new String();
private static String responseStr = new String();
private static int port = 2500;
public static void main(String args[]) {
System.out.println("Server is running.");
try {
socket = new ServerSocket(port);
while (true) {
connection = socket.accept();
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
DataOutputStream response = new DataOutputStream(connection.getOutputStream());
BufferedReader input = new BufferedReader(inputStream);
command = input.readLine();
response.writeBytes(responseStr);
response.flush();
}
} catch (IOException e) {
System.out.println("Fail!: " + e.toString());
}
}
I have the following PHP code:
<?php
$socket = stream_socket_server("tcp://192.168.0.10:2500", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
fclose($conn);
}
fclose($socket);
}
I start the java app, which starts fine, When I run the php, I get the following error:
An attempt was made to access a socket in a way forbidden by its access permissions. (0)
I have searched Google and have tried all the solutions I could find although nothing has worked. I have restarted both machines and disabled the firewall, neither worked.
I am not sure where to go from here.
[update from comment:]
192.168.0.10 is the machine with the java app and web server on it. I am connecting from another machine 192.168.0.7
You can only can create a socket on the machine were the code is running on.
So if the PHP code is run on 192.168.0.7, then do:
$socket = stream_socket_server("tcp://192.168.0.7:2500", $errno, $errstr);

testing a client server

I wrote a server that listens for client messages, it's a variation of http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html. I wrote them both in eclipse as java classes in the same project. To test it I have a client class with a main that starts the server and then sends messages to it. When I run it the program just hangs at serverSocket.accept(); according to the javadoc for ServerSocket accept is not asynchronous? That would explain the hanging, but then how does the tutorial code work then?
UPDATE - here is my working code:
Here is the working code:
MyServer.java
/*imports neglected for brevity */
public class MyServer {
public static final String hostname = "localhost";
public static final int portNum = 4444;
ServerSocket serverSocket;
BufferedReader serverReader;
File serverLog;
FileWriter fw;
BufferedWriter serverWriter;
Socket clientSocket;
public static void main(String[] args) {
MyServer server = new MyServer(portNum);
// start the server so it can listen to client messages
server.start();
}
public MyServer(int portNum) {
try {
// endpt for server side, used to listen for client socket
serverSocket = new ServerSocket(portNum);
/* have server socket listen for connection, return client socket.
* serverSocket can now talk to clientSocket
*/
clientSocket = serverSocket.accept();
// server writes messages to this log
serverLog = new File("ServerLog.txt");
if(!serverLog.exists())
serverLog.createNewFile();
fw = new FileWriter(serverLog.getAbsoluteFile());
serverWriter = serverWriter = new BufferedWriter(fw);
/* server reads from this stream that is populated by the client's
* OUTPUT stream/client socket's INPUT stream
*/
serverReader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void start() {
String clientMsg;
try {
while((clientMsg = serverReader.readLine()) != null) {
if(clientMsg.startsWith("exit")) {
break;
}
serverWriter.append(clientMsg);
}
serverWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyClient.java
public class MyClient {
public static final String hostname = "localhost";
public static final int portNum = 4444;
public static void main(String[] args) {
String msg = "message 1";
try {
// server is listening on http://localhost:4444
Socket serversSocket = new Socket(hostname, portNum);
PrintWriter clientOut = new PrintWriter(serversSocket.getOutputStream(), true);
// send first message
clientOut.println(msg);
msg = "message 2";
// send second message
clientOut.println(msg);
msg = "exit";
// this will stop the server
clientOut.println(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
If you go through the tutorial it creates two applications one with client one with server.
You cannot create a variation like this as, when you call the constructor, your whole application blocks in clientSocket = serverSocket.accept();.
If you insist on creating a single application for whatever reason, you can do multithreading. But I do not see any reason why you would want to do that.
The tutorial assumes you are not running them in the same program. If you must run them in the same program, then start your server in a separate thread.
if you have an android phone you can test this with the app TCP socket
make sure you PortForward the port the server is listening to.
some isp also block ports so make sure with your isp that all ports are open
trust me broke my head on this one :)
http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html
also make sure your server has the public ip and not local ip
if you test this localy then the code above is fine if not you will need to add
bind(SocketAddress endpoint)
/*Binds the ServerSocket to a specific address (IP address and port number).*/
you can find your ip by typeing in google: whats my ip

Categories

Resources