I am new to Java programming and am trying to develop multi-client chat server.
following is my code:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
public class server implements Runnable{
private List<ServerClient> clients = new ArrayList<ServerClient>();
//private String UID;
private int port;
private ServerSocket socket;
private Thread run, manage, send, receive;
private boolean running = false;
public int i=0;
public server(int port){
// this.UID = UID;
this.port = port;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
run = new Thread(this, "Server");
run.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
running = true;
ManageClients();
receive();
}
private void ManageClients(){
manage = new Thread("Manage"){
public void run(){
while(running){
//managing
}
}
};
manage.start();
}
private void receive(){
receive = new Thread("Receive"){
public void run(){
Socket S1 = null;
try {
S1 = socket.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(running){
/* byte [] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String string = new String(packet.getData());
System.out.println(string);*/
/* BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String string = br.readLine();
System.out.println(string);
process(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
process(S1);
System.out.println(String.valueOf(i));
i++;
}
}
};
receive.start();
}
private void process(Socket S1){
BufferedReader br = null;
String string = "";
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
string = br.readLine();
System.out.println(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(string.startsWith("/c/")){
clients.add(new ServerClient("name", S1.getInetAddress(), S1.getPort(), "UID"));
}
else if(string.startsWith("/ip/")){
//send ip address to raspberry
System.out.println(string);
}
else if(string.startsWith("/r/")){
//send relay command to relay
System.out.println(string);
}
}
}
The server is accepting only one connection. If I try to connect another user the console does not show any output.
Can you please guide where I am going wrong.
Thank you
You need to run the accept method multiple times... once for each client that wants to connect. Typically people do that on a separate thread in a while loop since the accept method is blocking.
In your code it seems like you are only calling accept once, and hence you will only get one client connection.
I would recommend that you change your code architecture here, but if you want to keep it the same, and you know how many clients will connect, then you could wrap your access to socket in a synchronization lock, and call your receive method once for each client.
Related
I am trying to implement a server and client based on the web socket technologie but when I run the TCPDataServer class I am getting the following error:
java.io.IOException: connection reset
at java.io.DataInputStream.read(Unknown Source)
at org.server.ClientWorker.run(TCPDataServer.java:67)
at java.lang.Thread.run(Unknown Source)
I excepted to get the following output Hello, I am Alex!
TCPDataClient
package org.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPDataClient {
public static void main(String[] args) {
try {
TCPDataClient obj = new TCPDataClient();
Socket obj_client = new Socket(InetAddress.getByName("127.0.1"), 1000);
DataInputStream din = new DataInputStream(obj_client.getInputStream());
DataOutputStream dout = new DataOutputStream(obj_client.getOutputStream());
byte[] buffer = obj.createDataPacket("Hello, I am Alex!".getBytes("UTF8"));
dout.write(buffer);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private byte[] createDataPacket(byte[] data) {
byte[] packet = null;
try {
byte[] initialize = new byte[1];
initialize[0] = 2;
byte[] separator = new byte[1];
separator[0] = 4;
byte[] data_length = String.valueOf(data.length).getBytes("UIF8");
packet = new byte[initialize.length + separator.length + data_length.length + data.length];
System.arraycopy(initialize, 0, packet, 0, initialize.length);
System.arraycopy(data_length, 0, packet, initialize.length, data_length.length);
System.arraycopy(separator, 0, packet, initialize.length + data_length.length, separator.length);
System.arraycopy(data, 0, packet, initialize.length + data_length.length + separator.length, data.length);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return packet;
}
}
TCPDataServer
package org.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.logging.Level;
import com.sun.istack.internal.logging.Logger;
public class TCPDataServer {
public static void main(String[] args) {
try {
ServerSocket server_socket = new ServerSocket(1000);
while (true) {
new Thread(new ClientWorker(server_socket.accept())).start();
}
} catch (IOException e) {
System.err.println("Error");
System.err.println(e);
System.err.println("\n2");
System.err.println(e.getMessage());
System.err.println("\n3");
System.err.println(e.getLocalizedMessage());
System.err.println("\n4");
System.err.println(e.getCause());
System.err.println("\n5");
System.err.println(Arrays.toString(e.getStackTrace()));
System.err.println("\n6");
e.printStackTrace();
}
}
}
class ClientWorker implements Runnable {
private Socket target_socket;
private DataInputStream din;
private DataOutputStream dout;
public ClientWorker(Socket recv_scket) {
try {
target_socket = recv_scket;
din = new DataInputStream(target_socket.getInputStream());
dout = new DataOutputStream(target_socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] initilize = new byte[1];
try {
din.read(initilize, 0, initilize.length);
if (initilize[0] == 2) {
//This is line 67.
System.out.println(new String(readStream()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private byte[] readStream() {
byte[] data_buff = null;
try {
int b = 0;
String buff_length = "";
while ((b = din.read()) != 4) {
buff_length += (char) b;
}
int data_length = Integer.parseInt(buff_length);
data_buff = new byte[Integer.parseInt(buff_length)];
int byte_read = 0;
int byte_offset = 0;
while (byte_offset < data_length) {
byte_read = din.read(data_buff, byte_read, data_length - byte_offset);
byte_offset += byte_read;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data_buff;
}
}
In your Server program you have used din as your input stream reader which reads from the socket.
In your Client program you have used dout as output stream writer which writes to the underlying socket
In your ClientWorker class you have given multiple read operations using dinfrom the socket, whereas you have given only one write operation to the stream using dout object.
The din object will be blocking/waiting to receive the data from client side, but unfortunately you would have closed (program ends) your socket connection on your client which is reason for the DataInputStream to throw IOException.
And your din object will throw an IO error if your underlying socket/stream has been close and yet you are trying read using it.
Try to maintain the same number of reads and writes on either side (client/server).
You aren't closing the sockets, so your OS is resetting them when the JVM exits.
I am getting started with java sockets just out of inquisitiveness.
I wrote a small piece of code, a server and a client.
The server accepts a string and converts it to upper case and returns to the client.
I want the server to be able to handle multiple clients and have a persistent connection.
Here is the server code :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
private ServerSocket listener;
private ArrayList<Socket> clients;
public Server() throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(7575);
}
public Server(int port) throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(port);
}
public void start() throws IOException, InterruptedException{
Thread one = new Thread(){
public void run(){
while (true){
Socket socket = null;
try {
socket = listener.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (socket.isConnected()){
try {
socket.setKeepAlive(true);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clients.add(socket);
System.out.println(socket.getRemoteSocketAddress().toString());
}
}
}
};
Thread two = new Thread(){
public void run(){
try {
while (true){
work();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
one.start();
two.start();
one.join();
two.join();
stop();
}
private void stop() throws IOException{
listener.close();
}
private void work() throws IOException{
if (clients.size() == 0){
return;
}
for(int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (!socket.isClosed()){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String data = br.readLine();
if (data == null) continue;
out.println(data.toUpperCase());
}
else{
clients.remove(socket);
}
}
}
}
package entry;
import java.io.IOException;
import server.Server;
public class Main {
public static void main(String args[]) throws IOException{
Server server = new Server();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is the client :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[])throws IOException{
Socket socket = new Socket("192.168.0.110", 7575);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream(), true);
while (true){
System.out.println("\n\nEnter a string : ");
String inp = br.readLine();
if (inp.equals("quit")) break;
pr.println(inp);
System.out.println("The response is : " + sr.readLine());
}
socket.close();
}
}
Strange thing here is when I set a breakpoint in the server code and step through the code in eclipse, the code is working exactly as expected i.e I am getting the response in the client.
But when I run it directly in eclipse, I am not getting the response in the client.
Cannot understand what is going wrong.
Edit
I seem to have fixed the issue.
Here is the code snippet :
Thread two = new Thread(){
public void run(){
try {
while (true){
Thread.sleep(1000); //This is the added line
work();
}
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
But I am still confused about what made the timing difference.
Is there any cleaner way to achieve this ?
I've solved the problem with a different approach.
Here is the new Approach:
ServerHandler.java :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerHandler extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private ArrayList<Socket> clients;
public ServerHandler(Socket socket) throws IOException{
this.socket = socket;
clients = new ArrayList<Socket>();
if (!clients.contains(socket)){
clients.add(this.socket);
System.out.println(this.socket.getRemoteSocketAddress());
}
}
#Override
public void run(){
while (true){
if (clients.isEmpty()) break;
String str = null;
for (int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (socket.isClosed()){
clients.remove(socket);
continue;
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
str = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(str.toUpperCase());
}
}
}
}
Main.java [for running the server] :
package entry;
import java.io.IOException;
import java.net.ServerSocket;
import server.ServerHandler;
public class Main {
public static void main(String args[]) throws IOException{
ServerSocket listener = new ServerSocket(7575);
try{
while (true){
new ServerHandler(listener.accept()).start();
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
listener.close();
}
}
}
Ok, Here we go.I don't understand the use of Arraylist for maintaining Connections unless You are handling the messy details for each Client.
The most used or prefered approach for handling multiple clients at a time can be understood in terms of an example:
Server.java
import java.net.ServerSocket;
import java.io.IOException;
class Server {
public static void main(String[] args) throws IOException {
try( ServerSocket ss = new ServerSocket(3333)) { // try with resources
new ServerThread(ss.accept()).start();
}
}
}
As you can see, I just defined a Class that will listen for Client connections, and as soon a request is made to the server it will start a Thread which is defined in the next class. A point to be noted here is the use of Try-with-Resources block. Any class that implements the Closeable interface can be enclosed within this try statement. The try-with-resources automatically handles closing of streams or connections for me. This means, you remove all your redundant try-catch blocks from your code and use this try instead.
Now,
ServerThread.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket s = null;
public ServerThread(Socket s) {
super("ServerThread");
this.s = s;
}
public void run() {
try( PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("In Server");
String in, out;
while ((in = stream.readLine()) != null) {
System.out.println("Msg 4m client: " + in);
if(in.equals("bye"))
break;
out = write.readLine();
pw.println(out);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Observe the try-with-resources statement over here, We can initialize multiple Connections/Input-Output Streams here, All of the opened connection will automatically be closed as soon as the compiler returns from try statement.Also, Observe the while statement, it will keep on running until the client is sending messages, and will quit if the message is "bye".
Finally, a Client program that sends request to the server.
Client.java
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Client {
public static void main(String[] args) {
try( Socket s = new Socket("localhost", 3333);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in)) ) {
System.out.println("In Client");
String in;
while ((in = write.readLine()) != null) {
pw.println(in);
if(in.equals("bye"))
break;
System.out.println("Msg 4m server: " + stream.readLine());
}
} catch(IOException e) {
System.err.println("Exception: " + e);
}
}
}
Notice, the while Statement here, it will loop until the user is entering messages, and if the message is "bye", it will quit.Rest of the program can be easily understood from above explanation.
I am trying to code a chat in my java software,
i have 2 eclipses running on my windows 7.
one of the eclipses includes a project "ServerListener" which contains a class Server.java
and the other eclipse includes a project "Client" and contains a class cl.java.
I am sending messages from my cl.java to the server.java
each time the server receives a message he send it back to the cl.java (the one i sent the message from) to make sure it's connected.
(THIS PART WORKS FINE sending message to the server and back from the server to the same client)
my question is :
how to let the server.java send the message to another client instead of the original client?
if i run another eclipse with the same project as "Client"
i want to the two eclipses to chat together
this is the Server.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();
public static void main(String[] args) {
new Server();
}
public Server() {
// ServerSocket is only opened once !!!
try {
serverSocket = new ServerSocket(6000);
System.out.println("Waiting on port 6000...");
boolean connected = true;
// this method will block until a client will call me
while (connected) {
Socket singleClient = serverSocket.accept();
// add to the list
ServerThread myThread = new ServerThread(singleClient);
allClients.add(myThread);
myThread.start();
}
// here we also close the main server socket
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServerThread extends Thread {
Socket threadSocket;
String msg;
boolean isClientConnected;
InputStream input;
ObjectInputStream ois;
OutputStream output;
ObjectOutputStream oos; // ObjectOutputStream
public ServerThread(Socket s) {
threadSocket = s;
}
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
input = threadSocket.getInputStream();
ois = new ObjectInputStream(input);
output = threadSocket.getOutputStream();
oos = new ObjectOutputStream(output);
// get the user name from the client and store
// it inside thread class for later use
//msg = (String) ois.readObject();
isClientConnected = true;
//System.out.println(msg);
for(ServerThread t:allClients)
t.sendText("User has connected...");
// send this information to all users
// dos.writeUTF(userName + " has connected..");
// for(ServerThread t:allClients)
// t.sendText(msg);
while (isClientConnected) {
System.out.println("connect ... ");
try {
msg = (String) ois.readObject();
System.out.println(msg);
if (msg.equals("quit"))
break;
for (ServerThread t : allClients)
t.sendText(msg);
} catch (Exception e) {
}
}
// close all resources (streams and sockets)
ois.close();
oos.close();
threadSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
this is the client (cl.java):
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;
static ConnectThread clientThread;
boolean isConnected;
static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
public static void main(String[] args) {
new cl();
}
public cl() {
connectUser();
}
public void connectUser() {
clientThread = new ConnectThread();
clientThread.start();
}
class ConnectThread extends Thread {
InputStream input;
OutputStream output;
ObjectOutputStream oos;
Socket s;
public void sendText(String text) {
try {
System.out.println("sending text to server..");
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
s = new Socket(HOST, PORT);
output = s.getOutputStream();
oos = new ObjectOutputStream(output);
isOnline = true;
isConnected = true;
new ListenThread(s).start();
while (isOnline) {
System.out.println("Enter a Text to send:");
msg = scanner.nextLine();
clientThread.sendText("amjad: " + msg);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ListenThread extends Thread {
Socket s;
InputStream input;
ObjectInputStream ois;
public ListenThread(Socket s) {
this.s = s;
try {
input = s.getInputStream();
ois = new ObjectInputStream(input);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while (isConnected) {
try {
final String inputMessage = (String) ois.readObject();
System.out.println(inputMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
thanks in advance
I created a console chatapplication, that waits for user input with bufferedreader.readline() and should print chat messages from the partner simultaneously. But after readline() was invoked, no output is possible.
Waiting for messages and Sending Messages is realized in different threads.
public class MsgReader implements Runnable {
private Socket connection;
private final Console con;
public MsgReader(Socket sock, Console con) {
this.connection = sock;
this.con = con;
this.run();
}
#Override
public void run() {
InputStream is = null;
try {
is = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
try {
System.out.println("asdf");
while (true) {
String ss = in.readLine();
// System.out.println((char)in.read());
// System.out.println("asdf");
//
con.write(ss);
// con.write(ss);
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class MsgWriter implements Runnable {
private Socket connection;
private final Console con;
public MsgWriter(Socket sock, Console con) {
this.connection = sock;
this.con = con;
this.run();
}
#Override
public void run() {
OutputStream os = null;
try {
os = connection.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
try {
char in = ' ';
boolean running = true;
while (true) {
String ss=In.inString2("");
if(ss.equals("")){
System.out.println("enter your message: ");
//String s = con.readLine();
String s=In.inString2("");
bw.write(s+"\n");
bw.flush();
System.out.println("sent");
}
if(ss.equals("x")){
break;
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("fail ");
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
console
import inout.In;
public class Console {
public Console() {
}
public synchronized void write(String txt) {
System.out.println(txt);
}
public synchronized String readLine() {
String temp=In.inString2("");
return temp;
}
}
Calling run() doesn't start a new thread, it just executes the method. You need to create a new Thread:
Runnable runnable = ...
Thread thread = new Thread(runnable);
thread.start() // <-- actually causes the run() method to be executed asynchronously
Better still would be to use an ExecutorService:
ExecutorService executor = ...
executor.execute(runnable);
As these offer pooling of threads (amongst other features).
I am running a client on android emulator and server (java) on the same PC and am using socket programming. Attaching code below. Individually both are running fine but the actual data transfer is not happening and am not able to figure it out.
Server side(PC):
import java.net.*;
import java.io.*;
public class Server_tcp {
void run(){
{
try {
System.out.println("In 1st try blck");
try {
System.out.println("In 2nd try blck");
Boolean end = false;
ServerSocket ss = new ServerSocket(4444);
System.out.println("socket created");
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
System.out.println("socket accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
System.out.println("Tcp Example" + "From client: "+st);
output.println("Good bye and thanks for all the fish :)");
s.close();
if (st==null){ end = true; }
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException exp) {
// TODO Auto-generated catch block
exp.printStackTrace();
}
}
}
public static void main(String args[])
{
Server_tcp server = new Server_tcp();
while(true){
server.run();
}
}
}
Client Side (Android ):
package com.try3;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import java.io.*;
import java.net.*;
public class ClientTCPActivity extends Activity {
/** Called when the activity is first created. */
private EditText et;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("Before try net");
trynet();
System.out.println("after try net");
}
public void trynet() {
System.out.println("inside try net");
try {
System.out.println("inside try");
Socket s = new Socket("127.0.0.1",4444);
//outgoing stream redirect to socket
OutputStream out = (OutputStream) et.getContentDescription();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
String st = input.readLine();
System.out.println(st);
//Close connection
s.close();
System.out.println(" try ");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
From the Android Emulator you should be referring to your PC using 10.0.2.2 instead of 127.0.0.1
I didn't understand what you are trying to do here.
OutputStream out = (OutputStream) et.getContentDescription();
PrintWriter output = new PrintWriter(out);
Did you mean something like:
PrintWriter output = new PrintWriter(s.getOutputStream(),true);
??