Пример проекта для IntelliJ IDEA. Для работы примера требуется json-simple, находится в архиве вместе с примером.
Текст программы:
import org.json.simple.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class testSocket {
private static String dec2hex(int i){
String result = "0000";
if (i >= 0 && i <= 15) { result = "000" + Integer.toHexString(i); }
else if (i >= 16 && i <= 255) { result = "00" + Integer.toHexString(i); }
else if (i >= 256 && i <= 4095) { result = "0" + Integer.toHexString(i); }
else if (i >= 4096 && i <= 65535) { result = Integer.toHexString(i); }
return result;
}
private static String convertToEntities (String tstr) {
StringBuilder bstr = new StringBuilder(tstr.length()*7);
String ttt = "";
for (int i = 0; i < tstr.length(); ++i) {
if (tstr.codePointAt(i) > 127) {
bstr.append(Character.toString((char) 92));
bstr.append("u");
ttt = dec2hex(tstr.codePointAt(i));
bstr.append(ttt.charAt(0));
bstr.append(ttt.charAt(1));
bstr.append(ttt.charAt(2));
bstr.append(ttt.charAt(3));
} else {
bstr.append(tstr.charAt(i));
}
}
return bstr.toString();
}
public static void main(String[] ar) {
// --- Server Connect Info ---
String host = "127.0.0.1";
int port = 2004;
// --- Service Const ---
String MagicPacket = "\u0017\u0006";
String cs_integration_api = "0077";
String iFlag = "30";
String CRLF = "\r\n";
String MCIAPI_CS_SendPrivateMessage = "0002";
// --- Message Params ---
int UserFrom = 1;
int UserTo = 2;
String Msg = "Hello!";
String hash = "random hash 123";
String APIStype = "anyName";
String ServerKey = "yourServerApiKey";
// --- JSON Structure For Send To Server ---
JSONObject resultJson = new JSONObject();
resultJson.put("UserTo", UserTo );
resultJson.put("UserFrom", UserFrom );
resultJson.put("Msg", Msg );
resultJson.put("hash", hash );
resultJson.put("APIStype", APIStype );
resultJson.put("ServerKey", ServerKey);
String sendData = "";
try {
// --- Connecting To Server ---
InetAddress ipAddress = InetAddress.getByName(host);
Socket socket = new Socket(ipAddress, port);
System.out.println("Server IP: " + host + " Port: " + port + "?");
// --- Create Read And Write Socket Streams ---
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// --- Init Message ---
sendData = "mc6.3" + CRLF + "{Secured: \"\"}" + CRLF;
// --- Send Init Message ---
out.write(sendData.getBytes(), 0, sendData.length());
out.flush();
// --- Read sc_hello Command From Server ---
in.readLine();
// --- Create Message ---
sendData = MagicPacket + cs_integration_api + iFlag + MCIAPI_CS_SendPrivateMessage + convertToEntities(resultJson.toString()) + CRLF;
// --- Send Message ---
out.write(sendData.getBytes(), 0, sendData.length());
out.flush();
// --- Read Send Result ---
System.out.println("Result: " + in.readLine());
} catch (Exception x) {
x.printStackTrace();
}
}
}
Скачать готовый проект с сайта