Trying to connect to my own POP3 server on localhost(1024 port). Its code:
server_socket = new ServerSocket(SBAP_PORT);
Socket clntSocket = server_socket.accept();
public void run() {
try {
try {
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()
));
out = new PrintWriter(socket.getOutputStream(), true);
out.print("+OK\\r\\n");
command = in.readLine();
String result = handleInput(command);
out.println(result);
} finally {
socket.close();
state.close();
System.out.println("client offline.");
}
} catch (Exception ignored) {
}
}
It's working fine with telnet, but when I try to do it with Thunderbird, just get timeout(Failed to find settings for your email account).
In debug I see, that I get null string while connecting.
What am I doing wrong? Maybe I should send something to client just after connecting?
I think it must be \r\n rather \\r\\n, plus try to flush for each response you send to the client by out.flush();, but it might not be necessary.
Related
i am working on an app in android studio and basiclly i need that whenever i clicked a specific button it will create a connection between the java client and python server.
I first checked when u enter the page\activity of the specific button if there is a wifi connection in the phone.
It works fine. then i tried to do this and it didnt work (Important to say that the current code make my phone and my app crash and stop)
simple server:
HOST = '192.168.1.21'
PORT = 9000
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
client_socket, client_address = server_socket.accept()
print 'Connect with ' + client_address[0]
data = client_socket.recv(1024)
print "data :"
print data
print " end"
if data == HOST+"/n":
print 'hi'
else:
i = 0
while i < 15:
print i
i += 1
client_socket.close()
server_socket.close()
if __name__ == '__main__':
main()
this is just to check a connection. it might look strange because of the host +/n in the if . i recently chenged it because i am new to java and dont know how the data is sent. but that is not the problem rn.
public void ButtonClicked(View view) {
EditText editText = findViewById(R.id.edit_text);
final String ip = editText.getText().toString();
Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
try {
InetAddress host = InetAddress.getByName(ip);
final Client client = new Client(host, 9000);
new Thread(new Runnable() {
public void run() {
try {
client.send(ip);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
client.send(ip);
}
catch (IOException e) {
System.out.println("Caught Exception: " + e.toString());
}
i read that in android studio 3.0 u need to create a thread when u send data.
the client class that u see here :
public class Client
{
private Socket socket = null;
private BufferedReader reader = null;
private BufferedWriter writer = null;
public Client(InetAddress address, int port) throws IOException
{
socket = new Socket(address, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void send(String msg) throws IOException
{
writer.write(msg, 0, msg.length());
writer.flush();
}
public String recv() throws IOException
{
return reader.readLine();
}
}
it might be just a simple thing that i dont know of but those are the codes and i cant connect to the server. i figured out that the server works fine because if im connecting from the phone to 192.168.1.21 on the net i receive the connection and it does thw little while.
ty for the help - i would like to get the simplest fixes because im new to java.(sorry if there where grammer\ spelling mistakes)
Edit- logcat for the crash
At the end of your log it says NetworkOnMainThread. In your code there is a line client.send(ip) below your seperate thread which is executed at the main thread.
How to use socket to setup a SMTP server? I don't want to use any library like WISER. I just want a very simple SMTP server. How to setup?
I have tried to use the following code. But it seems like wrong.
try {
// TODO code application logic here
InetSocketAddress isa = new InetSocketAddress(25);
ServerSocket server = new ServerSocket();
server.bind(isa);
System.out.println("Server starting...");
while (true) {
System.out.println("Waiting...");
Socket client = server.accept();
if (client != null) {
System.out.println("connected");
}
}
} catch (IOException ex) {
Logger.getLogger(Fakeserver.class.getName()).log(Level.SEVERE, null, ex);
}
If I make a socket connection from an application that is running on an application server, where does the returned data go? Is it necessary to create a receiving server socket in the application with a specified port, or is it received on the port at which the server is using to connect to the application and I just need to write something that will extract that data?
Here is the code to read from a socket. You are making socket connection to port 8080 in server. You don't have to worry about the OS -> Server port.
public static void readSocket() throws IOException {
try (Socket s = new Socket(InetAddress.getByName(new URL("Some Address").getHost()), 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
}
The socket is one end-point of two-way communication link between server and client programs of the network.
The returned data is sending to your client Socket object, lets call it clientSocket. You need to call clientSocket.getInputStream() to decode it.
No, you dont need to create a receiving server socket in the application. Your client program establishes a connection to the server on your given host and port. clientSocket can both send data to server and receive data from server.
For example the client side code:
private PrintWriter out = null;
private BufferedReader in = null;
public void listenSocket(){
//Create socket connection
try{
clientSocket = new Socket(HOST, PORT);
// use out object to send data to server applicaiton
out = new PrintWriter(clientSocket.getOutputStream(),
true);
// uses in object to receive data from server application
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + HOST);
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
I wrote small TCP chat client and server. At start running on localhost, and now i moved it to external host. Personally it works alright because i have my firewall disabled, however on another machine it fails getting IOException (at creating Socket). Tried adding port I'm using 9764 to inbound and outbound rules, later disabling firewall at all and it still didn't work getting same IOException. Any thoughts?
Error log: http://pastebin.com/zEbFbX4Y
Client code: https://github.com/karosas/Simple-tcp-chat-client
Exception is catched here:
try {
client = new ChatClient();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(that, "Unknown host exception");
} catch (IOException e) {
JOptionPane.showMessageDialog(that, "IOException");
e.printStackTrace();
}
which leads to ChatClient ->
public ChatClient() throws UnknownHostException, IOException {
server = new Socket(host,port);
out = new PrintWriter(server.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
sc = new ServerConn(server);
}
And it leads to ServerConn
private BufferedReader in = null;
public ServerConn(Socket server) throws IOException {
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
}
public void run() {
String msg;
try {
while((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch(IOException e ) {
System.err.println(e);
}
}
Thanks for anything.
What is happening is that on localhost the connection doesn't need permission to travel through your internet router's firewall but when it connects to a different internet router that router can reject you from the server if it doesn't whitelist that port so you need to go onto the internet router's NetBIOS (The internet router of the server) and then white-list the ports, usually under:
ADVANCED > NAT > VIRTUAL SERVERS/PORT FORWARDING.
For more info on how to do this read the internet routers manual.
EDIT:
What you are doing is trying to connect to a 127.*..** adress meaning it doesn't even go on your network. on server computer rightclick your task bar select task manager go to perforamce tab and select wifi then find the IpV4 address and use that instead of 127.7.13.129
I am writing an app which needs to receive a string from a server. The following code works if the IP Adress connected to is "127.0.0.1" (The Client and the server are on the same phone, just for testing purpose), but not if it is the "real" IP Adress of the phone.
Server:
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(1109);
} catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and
// accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the
// client.
os.println("Das ist ein Test immernoch");
publish("Fertig");
} catch (IOException e) {
publish("Fertig");
} catch (Exception e) {
publish("Fertig");
}
Client:
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
smtpSocket = new Socket();
smtpSocket.connect(new InetSocketAddress("46.114.153.58", 1109), 10000); //That is the critcal line, if the IP is "127.0.0.1" everything works perfectly fine
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
return "Fehler";
} catch (IOException e) {
return "Fehler";
}
if (smtpSocket != null && os != null && is != null) {
try {
os.writeBytes("HELO\n");
String s = is.readLine();
os.close();
is.close();
smtpSocket.close();
return s;
} catch (UnknownHostException e) {
//System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
//System.err.println("IOException: " + e);
}
}
return "Fehler";
}
EDIT: Hence this is an app for a mobile device, there is no router I can configure.
Add this to your code
if (Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
You might have to forward the port you are using on your router if you are planning on using ServerSocket with external connections.
If this is the ip address of your router and you are connecting your android mobile to the router through wifi , then you have to port forward the port 1109 in your router to your mobile.
If this is the ip address of your android mobile connected through data connection , then there will be some restrictions on your data provider blocking ports for security .
46.114.153.58 is this a static ip address or dynamic ?
If its a dynamic ip address , first check the availability of the ip address by pinging it.