【发布时间】:2017-10-10 22:57:37
【问题描述】:
我正在开发一个带有 Socket 的软件,它设置与服务器的连接(我在其中安装了 PgAdmin for DB)。 我创建了客户端和服务器代码,它们运行良好,但是当用户执行某些操作时,我不知道如何通过套接字发送数据。该软件就像一个社交网络,用户登录并查看来自其他登录用户的信息和新闻。
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){
}
}
所以这是接收字符串用户的客户端,但我需要做什么???创建另一个套接字连接? 请帮助我,插座让我发疯。 我必须使用套接字(我知道 RMI 更好)
【问题讨论】:
-
请参阅此问题以获取信息:stackoverflow.com/questions/10332799/…
-
只需以字符串、对象、字节的形式发送它——套接字有输出流,所以写入它。就像你要写东西到文件一样。
-
但是当我创建登录表单时,客户端已经在运行了?或者我在用户单击按钮时运行它?另外我需要控制用户访问,所以生成的套接字必须为用户创建一个会话
-
这是您实施工作流程的工作。 Socket 只是用来发送数据的。
标签: java eclipse multithreading sockets