📄 simpclient.java
字号:
/**
* <p>Title: Learning material for socket programming</p>
* <p>Description: SIMP: Simple Instant Message Protocol. SIMP server records who is online, and redirects
* messages to the correponding user. SIMP server waits on UDP port 8002, clients wait on UDP port 8003. SIMP server
* supports following commands: user, pass, send, ask, sendfile, bye.
* user command allowing a user to send his/her username to the server.
* pass command allowing a user to send his/her password to the server. Only the user command executed should
* the pass command be invoked. If the user-pass pair matches a record in the user list, the user is ready to working.
* ask command asking the server if a specific user is online, usage: ask user. If the user is online, the server
* returns yes, otherwise no.
* send command sending a message to a user, usage: send user. At the end of message, a single period is needed.
* sendfile command send a file to a user, usage: sendfile user file_full_path.
* NOTE: both messages and files should not exceed 512 bytes.
* Datagram format:
* user command: SIMP user username1
* pass command: SIMP pass username1 password
* ask command: SIMP ask username1 username2
* send command: SIMP send username1 username2 0-512 bytes message
* sendfile command: SIMP sendfile username1 username2 filename 0-512 bytes file data
* bye command: SIMP bye username1
* Server response:
* SIMP status_code
* status_code: 100, OK, 200, sending success, 300, client error, 400 server error.</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author BLiu
* @version 0.1
*/
import java.net.*;
import java.io.*;
import java.util.*;
public class SIMPClient {
String user;
SocketAddress sa;
DatagramSocket client;
boolean login = false;
public SIMPClient(String user, String serverIP) {
try {
sa = new InetSocketAddress(serverIP, 8002);
client = new DatagramSocket();
} catch (Exception e) {
e.printStackTrace(System.out);
}
this.user = user;
while (true) {
byte[] buf = new byte[100];
System.out.print("#");
try {
System.in.read(buf);
if (buf[0] == '?')
printHelp();
else {
handleInput(buf);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
public static void main(String[] args) {
if (args.length != 2) {
System.out
.println("ERROR!! USAGE: java SIMPClient username serverIP");
System.exit(1);
}
SIMPClient SIMPClient1 = new SIMPClient(args[0], args[1]);
}
void sendToServer(String s) {
try {
DatagramPacket dp = new DatagramPacket(s.getBytes(), s.length(), sa);
client.send(dp);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
void printHelp() {
System.out.println("Commands:");
System.out.println("pass passwd : login to the server");
System.out
.println("send user : send a message to user, end with a single . at the begin of a line");
System.out
.println("sendfile user file_full_path : send a file of less than 512 bytes to user");
System.out.println("ask user : ask server whether user is online ");
System.out.println("bye : quit this session");
System.out.println("? : print this help");
}
void handleInput(byte[] buf) throws Exception {
String[] tokens = new String(buf).trim().split(" ");
if (tokens[0].equals("pass")) {
handlePass(tokens[1]);
} else if (tokens[0].equals("send")) {
handleSend(tokens[1]);
} else if (tokens[0].equals("ask")) {
sendToServer("SIMP ask " + user + " " + tokens[1]);
} else if (tokens[0].equals("sendfile")) {
handleSendfile(tokens[1], tokens[2]);
} else if (tokens[0].equals("bye")) {
sendToServer("SIMP bye " + user);
System.out.print("SIMP bye " + user);
System.exit(0);
}
}
void handlePass(String pass) {
try {
sendToServer("SIMP pass " + user + " " + pass);
DatagramPacket dp = new DatagramPacket(new byte[2048], 2048);
client.receive(dp);
String res = new String(dp.getData()).trim();
if (res.equals("SIMP 100")) {// login sucessful.
login = true;
System.out.println("login sucessful");
// start the helper thread.
new ClientHelper(client).start();
} else {
System.out.println("bad username or password");
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
void handleSend(String u) {
StringBuffer s = new StringBuffer("SIMP send ");
s.append(user);
s.append(' ');
s.append(u);
s.append(' ');
while (true) {
try {
byte[] buf = new byte[100];
System.in.read(buf);
s.append(new String(buf));
if (buf[0] == '.')
break;
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
System.out.println(s);
sendToServer(s.toString());
}
void handleSendfile(String u, String f) throws Exception {
StringBuffer s = new StringBuffer("SIMP sendfile ");
s.append(user);
s.append(' ');
s.append(u);
s.append(' ');
s.append(f);
s.append(' ');
File file = new File(f);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] buf = new byte[2048];
int num = dis.read(buf);
while (num != (-1)) {
dis.read(buf, 0, num);
s.append(new String(buf));
dis.skip(num);
num = dis.read(buf);
}
dis.close();
System.out.println("The file "+f+"is send!");
sendToServer(s.toString());
}
class ClientHelper extends Thread {
DatagramSocket ds;
ClientHelper(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
try {
while (true) {
DatagramPacket dp = new DatagramPacket(new byte[2048], 2048);
ds.receive(dp);
String[] tokens = new String(dp.getData()).trim()
.split(" ");
if (tokens[1].equals("sendfile")) {
StringBuffer s = new StringBuffer();
System.out.println("Please input savefilepath:");
while (true) {
try {
byte[] buf = new byte[100];
System.in.read(buf);
if (buf[0] == '$')
break;
s.append(new String(buf));
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
String[] t = new String(s).trim().split(" ");
File file = new File(t[0]);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
String str = "";
for (int i = 0; i < 6; i++)
str = str + tokens[i];
dos.write(dp.getData(), str.length(),
dp.getData().length - str.length());
dos.close();
System.out.println("The file is save at " + t[0]);
} else
System.out.println(new String(dp.getData()));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -