Client Server Programming in java
I am just working on my assignment of client-server and found an program online of a server.java as:
import java.io.*;
import java.net.*;
public class MyServer{
public static void main(String [] args){
try{
开发者_高级运维 ServerSocket ssc = new ServerSocket(7500);
Socket newSsc = ssc.accept();
DataInputStream din = new DataInputStream(newSsc.getInputStream());
DataOutputStream dout = new DataOutputStream(newSsc.getOutputStream());
PrintWriter pw = new PrintWriter(dout);
pw.println("Hello! Welcome to vinit's server.");
boolean more_data = true;
while(more_data){
String line = din.readLine();
if(line == null){
more_data = false;
}
else{
pw.println("From Server "+line + "\n");
System.out.println("From Client "+line);
if(line.trim().equals("QUIT"))
more_data = false;
}
}
newSsc.close();
}
catch(IOException e){
System.out.println("IO error");
}
}
}
THen after I used this server by typing the command as
$ telnet 127.0.0.1 7500 Now I want to ask how my server will be getting null from client, i mean what should be entered so that server will get nullThanks in Advance.
You have to gracefully close the TCP connection, simply CTRL+C or killing the telnet program won't do, it'll result in an exception in the Java code.
This is a challenge with telnet, depending on your keyboard layout and OS.
$ telnet localhost 8080 Trying 127.0.0.1... Connected to localhost (127.0.0.1). Escape character is '^]'. ^] telnet> quit Connection closed.
Basically, once inside telnet you'll have to press the telnet escape key, which on my keyboard is CTRL+å and type quit
, and on an US keyboard probably is what the telnet program tells you, just CTRL+]
If you're using the netcat program instead of telnet, you can just hit ctrl+d , or pipe some text to it, and the connection will be closed normally.
echo "Some text" | nc localhost 7500
When you close the connection.
Enter Ctrl+C :)
精彩评论