Sockets - Communication between C# and JAVA Android - java

I have a JAVA application that is reading a message:
public void onClick(View view)
{
new Thread((new ClientThread())).start();
//Intent i = new Intent(MainActivity.this,Main2Activity.class);
// startActivity(i);
}
//Thread que inicia o socket
class ClientThread implements Runnable
{
#Override
public void run() {
try
{
InetAddress serveradress = InetAddress.getByName(server_IP);
Log.e("TCP","A conetar...");
socket = new Socket(serveradress,PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((mensagem = in.readLine()) != null)
{
mensagem_final += mensagem;
}
txt.setText(mensagem_final);
if(in.readLine() == null)
{
Log.e("TCP","Nao tem mensagens");
}
Log.e("MSG",mensagem);
socket.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Now I'm trying to create a server in C# and all extra code is freezing when I run the server. And I still cant get the message from C# server.
Servidor servidor = new Servidor();
servidor.server();
class Servidor
{
public void server()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TcpListener tcplistener = new TcpListener(IPAddress.Any, 6000);
tcplistener.Start();
TcpClient tcpclient = tcplistener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpclient.GetStream();
string welcome = "Ola";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
}
}
Any help? I use Servidor servidor = new Servidor();
servidor.server(); in another windowsform. This window forms load another windowsforms and should also load the server. But everything on the windowsforms just freezes. Maybe I need threads?

AcceptTcpClient is a blocking call, and it really needs to be handled by something that spawns a new thread each time it succeeds, but for a single instance just try wrapping in a new thread e.g.
Task.Factory.StartNew(() =>
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TcpListener tcplistener = new TcpListener(IPAddress.Any, 6000);
tcplistener.Start();
TcpClient tcpclient = tcplistener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpclient.GetStream();
string welcome = "Ola";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
});

Related

Connection with sockets between Java and C#

when I try to send or receive a message with the sockets I can not do it, in java it tells me that the conecction was denied while in c# it tells me that the port is already being used, in java I send my message by clicking a button and I receive it with a thread and in a similar way in c#, I would really appreciate if you could tell me what is wrong, I have tried everything but I can not find the answer, thanks.
Java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String mensaje = jTextField1.getText();
System.out.println(mensaje);
byte men[] = mensaje.getBytes();
Socket socket = null;
ObjectOutputStream out = null;
try {
socket = new Socket("127.0.0.1", 7000);
out = new ObjectOutputStream(socket.getOutputStream());
out.write(men, 0, men.length);
out.close();
socket.close();;
} catch (Exception e) {
e.printStackTrace();
}
}
class HiloReceptor extends Thread {
#Override
public void run() {
super.run();
while (true) {
try {
ServerSocket ss = new ServerSocket(7000);
Socket socketCanal = ss.accept();
ObjectInputStream ois = new ObjectInputStream(socketCanal.getInputStream());
byte[] mensaje = new byte[1024];
ois.read(mensaje, 0, mensaje.length);
String msgRecibido = new String(mensaje, 0 ,mensaje.length);
System.out.println(msgRecibido);
jLabel1.setText("Mensaje recibido: " + msgRecibido);
ois.close();
socketCanal.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
C#
private void button1_Click(object sender, EventArgs e)
{
try
{
String mensaje = textBox1.Text;
Console.WriteLine(mensaje);
byte[] men = UTF8Encoding.UTF8.GetBytes(mensaje);
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint endp = new IPEndPoint(ip, 7000);
TcpListener tcpListener = new TcpListener(endp);
tcpListener.Start();
//Socket socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Socket socket = tcpListener.AcceptSocket();
//socket.Connect(endp);
socket.Send(men, men.Length, 0);
socket.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error al enviar.\n" + ex);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (!backgroundWorker1.CancellationPending)
{
try
{
Console.WriteLine("entre al ciclo");
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint endp = new IPEndPoint(ip, 7000);
Socket s = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Bind(endp);
s.Listen(1);
Socket canal = s.Accept();
byte[] buffer = new byte[1024];
msg = "";
while (canal.Receive(buffer, buffer.Length, 0) > 0)
{
msg += Encoding.UTF8.GetString(buffer);
}
Console.WriteLine(msg);
backgroundWorker1.ReportProgress(1);
canal.Close();
s.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error.\n"+ ex);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 1)
{
label1.Text = "Mensaje recibido: " + msg;
}
}

Problem with sending .mkv files with socket in java

I am trying to send a .mkv file with a Java server socket. The file is beeing transmitted normally but when I try to open it with VLC Media Player it only shows the first second of the film and then the pircture freezes.
Server:
public class Server {
public void run_server(){
try {
ExecutorService executorService = Executors.newFixedThreadPool(100);
ServerSocket server = new ServerSocket(1234);
System.out.println("Waiting for client at port " + server.getLocalPort() + "\n");
while (true) {
Socket client = server.accept();
executorService.execute(new Handler(client));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server s = new Server();
s.run_server();
}
public class Handler implements Runnable {
private Socket client;
public Handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
System.out.println("client connected: " + client.getInetAddress());
FileInputStream fin = new FileInputStream("D:\\Filme\\Asterix und das Geheimnis des Zaubertranks (2018).mkv");
byte[] buffer = new byte[522231808];
fin.read(buffer,0,buffer.length);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.write(buffer,0,buffer.length);
} catch (Exception e) {
e.printStackTrace();
}
}
The client:
public static void main(String[] args) {
new Thread(new Client()).start();
}
#Override
public void run() {
try {
Socket client = new Socket("localhost", 1234);
DataInputStream in = new DataInputStream(client.getInputStream());
FileOutputStream fout = new FileOutputStream("D:\\test\\test.mkv");
byte[] buffer = new byte[522231808];
in.read(buffer,0,buffer.length);
fout.write(buffer,0,buffer.length);
} catch (IOException e) {
e.printStackTrace();
}
}
Where is the problem?
Thanks in advance
Try a smaller buffer:
byte[] buffer = new byte[16384];
for (int n = in.read(buffer); n > 0; n = in.read(buffer)) {
fout.write(buffer,0,n);
}

Multithreaded Client-Server socket programming in Java

I'm having an issue with a messaging app I'm working on and was hoping someone could point me in the right direction. I'm stuck on getting the client and server to communicate properly.
My client multicasts a message to 5 processes, which make their alterations on the server side and send them back to the client. This all works fine, however when I try to multicast a second time, the server is getting stuck reading and eventually gives me the error: W/System.err (with no other information) at the line I point out in the code.
Client code:
private class ClientTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... msgs) {
try{
String msg = msgs[0];
int ID = Integer.parseInt(msgs[1]);
ObjectOutputStream out;
clock++;
Message m1 = new Message(clock, msg, ID);
for (int i = 0; i < 5; ++i) {
String remotePort = REMOTE_PORT[i];
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(remotePort));
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(m1);
out.flush();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Message m2 = (Message)in.readObject();
proposed_seq_from_q = m2.seq_number;
all_proposed.add(proposed_seq_from_q);
socket.close();
}
agreed_deliver = Collections.max(all_proposed);
m1.set_seq_number(agreed_deliver);
for (int i = 0; i < 5; ++i) {
String remotePort = REMOTE_PORT[i];
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(remotePort));
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(m1);
out.flush();
socket.close();
}
} catch(ClassNotFoundException e){
Log.e(TAG, "ClientTask: ClassNotFoundException");
e.printStackTrace();
} catch (UnknownHostException e) {
Log.e(TAG, "ClientTask: UnknownHostException");
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "ClientTask: IOException");
e.printStackTrace();
}
return null;
}
}
Server code:
private class ServerTask extends AsyncTask<ServerSocket, String, Void> {
#Override
protected Void doInBackground(ServerSocket... sockets) {
ServerSocket serverSocket = sockets[0];
boolean listening = true;
try{
while(listening) {
Socket clientSocket = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Message m = (Message)in.readObject();
new_proposed = Math.max(new_proposed + 1, clock);
m.set_seq_number(new_proposed);
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(m);
holdback_queue.add(m);
// ******************************************************
// THIS IS WHERE IT IS CRASHING
// ******************************************************
m = (Message)in.readObject();
publishProgress(m.get_message());
}
}catch(Exception e){
Log.e(TAG, "FAIL");
e.printStackTrace();
}
return null;
}
I've tried everything I can think of but I'm unable to get the server to read the second message. Everything is working up and being passed through with no issues up until that exact point. Can anyone please tell me what I'm doing wrong?

Socket android framework doesn't send message

I'm trying to add a client socket in the file ViewRootImpl.java. I'm creating the socket in a new thread with an handler because I need to comunicate between threads. I'm sending a message to Vthread every time performTraversal is called.
Client code in ViewRootImpl.java:
public class Vthread extends Thread{
Viewhandler mViewhandler;
Handler mhandler;
Socket client;
BufferedReader in;
PrintWriter out;
String s;
String line;
Vthread(Viewhandler handler){
mViewhandler = handler;
in = null;
out = null;
s = "hello";
client = null;
}
#Override
public void run(){
Looper.prepare();
try{
client = new Socket("10.0.2.2", 60000);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
mhandler = new Handler(){
#Override
public void handleMessage(Message msg) {
try{
if(out != null && in != null && client != null){
out.println(s);
out.flush();
line = in.readLine();
}
}catch (IOException e) {
e.printStackTrace();
}
}};
Looper.loop();
}
}
The server code in the host:
Socket socket;
ServerSocket server;
SocketAddress sockaddr;
BufferedReader in = null;
PrintWriter out = null;
String line;
String s = "bye";
server = null;
try{
sockaddr = new InetSocketAddress("127.0.0.1", 60000);
server = new ServerSocket();
server.bind(sockaddr);
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}catch (IOException e) {
e.printStackTrace();
}
try{
System.out.println("connected");
while(!Thread.currentThread().isInterrupted()){
line = in.readLine();
System.out.println(line);
out.println(s);
}
if (server != null ) server.close();
}catch (IOException e) {
e.printStackTrace();
}
The connection is accepted but the server doesn't receive any message from client. A problem that I identified is that more than one process might be using the socket. So I used a file in the internal storage of my application to restric the socket to my application only, but the problem remains. Code to restrict the socket to my application:
if(mVthread.mhandler != null) {
try{
if(reader == null) reader = new BufferedReader(new FileReader(file));
Message msg = Message.obtain();
msg.arg1 = 1000;
mVthread.mhandler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
EDIT
The problem is that the client socket sends a message but the server doesn't receive it. Both sides are blocked in the receive function. Any idea on what I am doing wrong?

ObjectInputStream haults program

I am trying to send an ArrayList to a client on an android device. The server says it sent the object however on the android device it hangs. I have read around that when creating an ObjectInputStream, an ObjectOuputStream must be created first and then flushed. I have tried that however this is not working for me. I didn't post the code for getting the clients as its just simply reading from a textfile. The Client class is very basic with few properties such as username, password and friends arraylist of strings. Any help would be much appreciated.
Server:
public class Server {
private static final int port = 9001;
private static final String IPAddr = "xxxxxxxxxxx";
ServerSocket server = null;
ArrayList <Client> users = new ArrayList<Client>();
public Server(){
try{
server = new ServerSocket(port);
System.out.println("connected server on port" + port);
while(true){
System.out.println("waiting for connection my ip add is "+ InetAddress.getLocalHost().getHostAddress());
Socket clientsocket = server.accept();
System.out.println("Connect to client:"+ clientsocket.getInetAddress().getHostName());
ClientThread client = new ClientThread(clientsocket);
client.start();
}
} catch(IOException e) {
System.err.println("Could not listen on port");
}
}
//Thread
public class ClientThread extends Thread {
private Socket sckt = null;
public ClientThread(Socket sckt){
super("ClientThread");
this.sckt = sckt;
}
public void run(){
try{
PrintWriter out = new PrintWriter(sckt.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
ObjectOutputStream objectOutput = new ObjectOutputStream(sckt.getOutputStream());
objectOutput.flush();
String Username = input.readLine();
String Password = input.readLine();
System.out.println("recieved from client: "+ Username);
int ClientIndex = isClient(Username);
if (ClientIndex != -1){
if(users.get(ClientIndex).password.equals(Password)){
//password correct -> send friends
out.println("correct");
out.flush();
System.out.println(Username + " is correct");
LoadClientFriends(Username, ClientIndex);
objectOutput.writeObject(users.get(ClientIndex).Friends);
System.out.println("Friends sent");
} else {
//password incorrect -> retry
out.println("password");
System.out.println(Username + " has wrong password");
}
} else {
//not a registered client
out.println("wrong");
System.out.println(Username + " is not a client");
}
} catch(Exception e){
System.err.println("Couldnt connect to Client socket");
}
}
}
public static void main(String[] args){
Server svr = new Server();
}
}
Client/Android:
public class MainActivity extends ActionBarActivity {
//Varibles
EditText username;
EditText password ;
private static final int port = 9001;
private static final String IPAddr = "xxxxxxx";
//Methods
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
/* Drawable d = getResources().getDrawable(R.drawable.actionbar_background);
getActionBar().setBackgroundDrawable(d);*/
}
public void Login(View view) {
//connect to server
Thread myThread2 = new Thread(Connect);
myThread2.start();
}
public void Register(View view) {
Intent i = new Intent(this, register_screen.class);
startActivity(i);
}
Runnable Connect = new Runnable()
{
public void run()
{
try {
Socket connection = new Socket(IPAddr,port);
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter output = new PrintWriter(connection.getOutputStream(), true);
//Sent the username a password for verifaction
username = (EditText)findViewById(R.id.edtName);
password = (EditText)findViewById(R.id.edtPassword);
output.println(username.getText().toString());
output.flush();
output.println(password.getText().toString());
output.flush();
//Receive confirmation of client
String res = input.readLine();
if (res.contains("correct")){
ObjectOutputStream objectOutput = new ObjectOutputStream(connection.getOutputStream());
objectOutput.flush();
ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(connection.getInputStream())); //Error Line!
Object object = objectInput.readObject();
ArrayList<String> friends = (ArrayList<String>) object;
Intent intent = new Intent(MainActivity.this,chat_screen.class);
intent.putExtra("Friends", friends);
startActivity(intent);
}else if (res.contains("password")){
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
}else {
}
}catch (Exception e){
}
}
};
}
The error you see is due to multiple output stream format. Stick to either ObjectOutputStream/ObjectInputStream or PrintWriter/BufferedReader. I suggest ObjectOutputStream/ObjectInputStream.
Server code: Use objectOutPut for all writes.
// out.println("correct");
objectOutput.writeUTF("correct");
// Update code for password and wrong too - Use objectOutput.writeUTF("");
Client code: Use just ObjectInputStream instead of BufferedReader
Define the objectInput here instead:
// BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ObjectInputStream objectInput = new ObjectInputStream(connection.getInputStream());
PrintWriter output = new PrintWriter(connection.getOutputStream(), true);
// Read data as follows:
// String res = input.readLine();
String res = objectInput.readUTF();

Categories

Resources