我正在開發一個軟件,與套接字,設置與服務器的連接(我安裝PgAdmin的數據庫)。 我創建客戶端e服務器代碼,他們完美運行,但我不知道如何通過套接字發送數據,當用戶做一些行動。該軟件就像一個社交網絡,用戶可以登錄並查看其他用戶記錄的信息和新聞。客戶端服務器多線程套接字
public class LoginForm {
private JTextField EditUsername;
private JTextField EditEmail;
private static Client client;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
client = new Client();
client.connectToServer();
LoginForm window = new LoginForm();
window.Loginframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginForm() {
initialize();
}
...
...
String username = "USER"; client.SendToServer(username);
這是我首先將客戶端連接到服務器的登錄表單。然後當我需要發送信息到服務器時,我不知道我需要做什麼!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private BufferedReader in;
private PrintWriter out;
private static Socket socket;
private static String number ="0" ;
/**
* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Enter in the
* listener sends the textfield contents to the server.
*/
public Client() {
}
public void connectToServer() throws IOException {
String host = "localhost";
int port = 4000;
InetAddress address;
try {
address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "1";
String sendMessage = number;
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void SendToServer(String username){
}
}
所以這是客戶端接收字符串用戶,但我需要做什麼?創建另一個socket連接? 請幫我,套接字讓我發瘋。 我必須用戶插座(我知道RMI要好得多)
轉問這個問題的信息:http://stackoverflow.com/questions/10332799/client-server-client-communication-using-sockets ?rq = 1 –
只需以字符串,對象,字節的形式發送它 - 套接字具有輸出流,以便寫入它。這就像你會寫一些文件。 – Antoniossss
但是當我創建登錄表單時,客戶端已經在運行?或者我在用戶點擊按鈕時運行它?另外我需要控制用戶的訪問權限,所以生成的套接字必須爲用戶創建一個會話 – dvdLucka