I am making a Server Client System from which the client(android user) send message to the server(python socket). i have tried this at own level but it does not work..Code is shown Below.
Any Help is Aprecated
Socket Server Side
import socket
import threading
import pyaudio
PORT = 7800
HEADER = 64
FORMAT= "utf-8 "
DISCONNECT_MSG="!DISCONNECTED"
SERVER=socket.gethostbyname(socket.gethostname())
ADDR = (SERVER,PORT)
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(ADDR)
connection_list = []
def handle_clinet(conn,addr):
print(f"[NEW CONNECTION]{addr} Connected")
CONNECTED = True
while CONNECTED:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length=int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MSG:
CONNECTED = False
if msg == "Disconnect":
conn.close()
CONNECTED = False
print("Dissconnected From the User...")
else:
print(msg)
def start():
server.listen()
while True:
conn,addr = server.accept()
thread = threading.Thread(target=handle_clinet,args=(conn,addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.active_count() -1}")
connection_list.append(addr)
print(connection_list)
print("[Starting] the server...")
start()
Client Side
public class send extends AsyncTask<String,Void,Void> {
String message;
Socket socket;
PrintWriter pw ;
String ip = "198.168.**.***";
#Override
protected Void doInBackground(String... strings) {
try{
socket = new Socket(ip,7800);
pw= new PrintWriter(socket.getOutputStream());
pw.write("Hello World");
pw.flush();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
to send message i use
val sendcode = send()
message=iptextview.text.toString()
sendcode.execute(message)
If any other Suggestion on topic is also apricated.
Related
Can somebody explain to me what I am doing wrong.First time I try to implement TCP between Java and C#:
Sever code c#
`
public void CreateServer()
{
Thread thread = new Thread(() =>
{
IPAddress addr = IPAddress.Parse(localIP);
tcpListener = new TcpListener(addr, 5053);
if (tcpListener != null)
{
tcpListener.Start();
while (!end)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
Console.WriteLine("Client connected from "+ip);
NetworkStream clientStream = tcpClient.GetStream();
StreamReader reader = new StreamReader(clientStream, Encoding.UTF8);
try
{
string request = reader.ReadToEnd();
Console.WriteLine("Message from client: " + request);
Byte[] StringToSend = Encoding.UTF8.GetBytes("Server");
clientStream.Write(StringToSend, 0, StringToSend.Length);
Console.WriteLine("Sending response back");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
});
thread.Start();
}
`
Client code java
`
public class TCP {
private String IP;
private InetAddress server;
private Socket socket;
public TCP(String IP) {
this.IP = IP;
}
protected void runTCP() {
try {
server = InetAddress.getByName(IP);
socket = new Socket(server, 5053);
System.out.println("Client connected. Listening on port 5053");
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
try {
System.out.println("Sending data...");
if (socket.isClosed()) socket = new Socket(server, 5053);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print(message);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void getResponseServer() {
Thread thread = new Thread() {
#Override
public void run() {
try {
System.out.println("Attempting to get response...");
if (socket.isClosed()) socket = new Socket(server, 5053);
BufferedReader mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String mServerMessage = mBufferIn.readLine();
System.out.println("Server message: " + mServerMessage);
} catch (Exception e) {e.printStackTrace();}
}
};
thread.start();
}
}
`
Output on server I get when sending "Hello" from client to server:
Client connected from 192.16.... Message from client: Hello Sending response back Client connected from 192.16....
Output on client:
Client connected. Listening on port 5053 Sending data... Attempting to get response...
Never gets response... Why?
Tried researching but found nothing yet, tried other code but didnt work aswell...
sorry , I can't comment. maybe you can use telnet command to vertify c# code is corrent.
telnet ip port
first, locate problem, then solve it.
if server is ok , we can use nc command vertify client code, I have test your java code , except every send data will close socket , other is ok.
Fixed it by removing writer.close() cause that causes socket closing and makes another connection to the server by creating again the socket which makes the server wait for a stream of data and the client wait for a response...
System.out.println("Sending data...");
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println(message);
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
the question is totally rewritten since I have understood that previously it was really unclear.
I have created a Java Socket server with threads to accept multiple connection in order to handle php tcp requests.
The java server just for the testing purposes it reverse the string supplied from php.
Java server is hosted on a ubuntu server and the php is located on another machine.
The java server shows that php client is connected, but the php is not loading and the string is not sent.
From the codes given below what could be the mistake?
UPDATE
the problem is the received string from the Java server. I have checked with debugger and the BufferedReader is full of '\u0000' and server stops responding. The rest code and communication is working perfect.
How I can avoid those null characters or decode the string correct?
ReverseServer
import java.io.*;
import java.net.*;
public class ReverseServer {
public static void main(String[] args) {
int port = 10007;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
new ServerThread(socket).start();
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
ServerThread
import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
String text;
do {
text = reader.readLine();
String reverseText = new StringBuilder(text).reverse().toString();
writer.println("Server: " + reverseText);
} while (!text.equals("bye"));
socket.close();
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
PHP client
<?php
// websocket connection test
$host = "ip_of_server";
$port = 10007;
$message = "Hello";
echo "Message To server :".$message;
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP'));
$result = socket_connect($socket, $host, $port);
if ($result) {
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :" . $result;
}
socket_close($socket);
I am trying to read a line, but on the string given on the php client didn't had the carriage return symbol "\r".
Once I have put this on the string it works as expected.
I'm creating two program files (one client one server).
Each file has one thread (one thread for server, one thread for client)
At runtime, there is supposed to be only one server, and there is supposed to be multiple and/or potentially infinite number of clients connecting to the server at the same time)
In order to get multiple clients to run, the user opens multiple command prompt / mac terminal windows (each window being one client) (one window being the server, so it requires at least two windows to run)
Once a client is connected, it can send messages (utf-8 strings) to the server. It will also receive from the server all messages sent from the other connected clients (it will not receive messages sent from itself).
The port number I am using to connect is 5344 (localhost).
Screenshot of client error:
Screenshot of server (no errors):
The error message is:
Exception in thread “Thread-75562” java.lang.NullPointerException at ChatClient$1.run(ChatClient.java:39)
The "39" is the line of code (I think) that the error is pointing at.
Screenshot of line 39 in ChatClient.java:
I have notice that some people use
Socket socket = new Socket(host, portNumber);
without calling any Socket.connect(host, portNumber); to connect to a server.
Does socket.connect() ever need to be used to connect a client to a server?
Code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
private static Socket Socket;
static int numberOfClients = 0;
public static void main(String args[])
{
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
String host = "localhost";
int numberOfClients = 0;
Thread ChatClient1 = new Thread ()
{
public void run()
{
try
{
//Client begins, gets port number, listens, connects, prints out messages from other clients
int port = 0;
int port_1number1 = 0;
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
if(args.length>0)
{
port = Integer.valueOf(port_number1);
}
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
try
{
Socket.connect(null);
}
catch (IOException e1)
{
e1.printStackTrace();
}
System.out.println("Client has connected to the server");
boolean KeepRunning = true;
while(KeepRunning)
{
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
try
{
//client creates new message from standard input
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
}
catch (IOException e)
{
e.printStackTrace();
}
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input encoded in UTF-8 string format
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
input=null;
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//Sending the message to server
String sendMessage = newmessage;
try
{
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(sendMessage + "\n");
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Message sent to server: "+sendMessage);
}
}
finally
{
}
}
};
ChatClient1.start();
}
}
}
Code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
private static Socket socket;
public static void main(String args[])
{
Thread ChatServer1 = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
int port_number1 = 0;
int numberOfClients = 0;
boolean KeepRunning = true;
if(args.length>0)
{
port_number1 = Integer.valueOf(args[0]);
}
System.out.println("Waiting for connections on port " + port_number1);
try
{
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//create a list of clients
ArrayList<String> ListOfClients = new ArrayList<String>();
//connect to client
// socket = serverSocket.accept();
//add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
ListOfClients.add("new client");
numberOfClients += 1;
System.out.println("A client has connected. Waiting for message...");
ListOfClients.add("new client" + numberOfClients);
//reading encoded utf-8 message from client, decoding from utf-8 format
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
//relaying message to every other client besides the one it was from
for (int i = 0; i < ListOfClients.size(); i++)
{
if(ListOfClients.get(i)!="new client")
{
String newmessage = null;
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null)
{
socket.close ();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
ChatServer1.start();
}
}
My question is: How to resolve the error and/or should I delete the socket.connect() while somehow still being able to connect to the server as a client?
I'm creating two program files (one client one server).
Each file has one thread (one thread for server, one thread for client)
At runtime, there is supposed to be only one server, and there is supposed to be multiple and/or potentially infinite number of clients connecting to the server at the same time)
In order to get multiple clients to run, the user opens multiple command prompt / mac terminal windows (each window being one client) (one window being the server, so it requires at least two windows to run)
Once a client is connected, it can send messages (utf-8 strings) to the server. It will also receive from the server all messages sent from the other connected clients (it will not receive messages sent from itself).
Screenshot of exception in thread / array index out of bounds error (eclipse):
Screenshot of Socket Exception error (server):
Screenshot of error on client side:
Code of Server (ChatServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
ChatServer chatserver = new ChatServer();
private static Socket socket;
public static void main(String args[])
{
Thread ChatServer1 = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
int port_number1 = 0;
int numberOfClients = 0;
boolean KeepRunning = true;
if(args.length>0)
{
port_number1 = Integer.valueOf(args[0]);
}
System.out.println("Waiting for connections on port " + port_number1);
try
{
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//create a list of clients
ArrayList<String> ListOfClients = new ArrayList<String>();
//connect to client
// socket = serverSocket.accept();
//add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
ListOfClients.add("new client");
numberOfClients += 1;
System.out.println("A client has connected. Waiting for message...");
ListOfClients.add("new client" + numberOfClients);
//reading encoded utf-8 message from client, decoding from utf-8 format
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
//relaying message to every other client besides the one it was from
for (int i = 0; i < ListOfClients.size(); i++)
{
if(ListOfClients.get(i)!="new client")
{
String newmessage = null;
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null)
{
socket.close ();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
ChatServer1.start();
}
}
Code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
static int numberOfClients = 0;
public static void main(String args[])
{
ChatClient chatclient = new ChatClient();
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
String host = "localhost";
int numberOfClients = 0;
Thread ChatClient1 = new Thread ()
{
public void run()
{
try
{
//Client begins, gets port number, listens, connects, prints out messages from other clients
int port = 0;
int port_1number1 = 0;
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
if(args.length>0)
{
port = Integer.valueOf(port_number1);
}
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
boolean KeepRunning = true;
while(KeepRunning)
{
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
try
{
Socket clientSocket = new Socket("localhost", port);
InetAddress inetlocalhost = InetAddress.getByName("localhost");
SocketAddress localhost = new InetSocketAddress(inetlocalhost, port);
clientSocket.connect(localhost, port);
System.out.println("Client has connected");
//client creates new message from standard input
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
}
catch (IOException e)
{
e.printStackTrace();
}
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input encoded in UTF-8 string format
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
input=null;
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//Sending the message to server
String sendMessage = newmessage;
try
{
Socket clientSocket = new Socket("localhost", port);
SocketAddress localhost = null;
clientSocket.connect(localhost, port);
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(sendMessage + "\n");
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Message sent to server: "+sendMessage);
}
}
finally
{
}
}
};
ChatClient1.start();
}
}
}
My question is: How should I go about resolving all three errors (it seems like if I change one part of the code, then the other errors will either still exist or be resolved due to that but I could be wrong)? I would also like to know if there's a way to list the number of clients in an arraylist in the server code so that when a client closes their window I can keep the server up by just removing them from the list.
I have a server on node.js and client on Java. When client of Java connects to Nodejs server then it shows me error which is given below.
I have a Server on node.js
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello from server\r\n');
c.pipe(c);
});
server.on('data', ()=>{
Console.log(data);
});
server.on('error', (err) => {
throw err;
});
server.listen(6969, () => {
console.log('server bound');
});
I hava a java code.
public class NodeJsEcho {
// socket object
private Socket socket = null;
public static void main(String[] args) throws UnknownHostException,
IOException, ClassNotFoundException {
// class instance
NodeJsEcho client = new NodeJsEcho();
// socket tcp connection
String ip = "127.0.0.1";
int port = 6969;
client.socketConnect(ip, port);
// writes and receives the message
String message = "message123";
System.out.println("Sending: " + message);
String returnStr = client.echo(message);
System.out.println("Receiving: " + returnStr);
}
// make the connection with the socket
private void socketConnect(String ip, int port) throws UnknownHostException,
IOException{
System.out.println("[Connecting to socket...]");
this.socket = new Socket(ip, port);
}
// writes and receives the full message int the socket (String)
public String echo(String message)
{
try {
// out & in
PrintWriter out = new PrintWriter(getSocket().getOutputStream(),
true);
BufferedReader in = new BufferedReader(new
InputStreamReader(getSocket().getInputStream()));
// writes str in the socket and read
out.println(message);
String returnStr = in .readLine();
return returnStr;
} catch (IOException e)
{
e.printStackTrace();
}
return null;
} // get the socket instance
private Socket getSocket()
{
return socket;
}
}
Its shows me the error on server side of:
client connected
events.js:141
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:870:11)
at TCP.onread (net.js:550:26)
Done.
You are not closing the socket on the client side - causing connection reset.
// In echo()
in.close();
out.close();
// In main()
getSocket().close();