Swing applet中使用的套接字我应该用Java做一个基于Swing和gui的服务器&客户机,我需要做一个套接字,从服务器到客户端,从客户机到服务器,然后传递某种字符串,我希望稍后有一个函数,根据套接字中的字符串做一些事情。由于某些原因,我找不到一个简单的代码示例来展示它是如何以简单的方式完成的。任何人都有任何简单的例子,或者可以解释它是如何完成的?
2 回答
忽然笑
TA贡献1806条经验 获得超5个赞
public static void main(String[] args) throws
UnknownHostException, IOException, InterruptedException {
Thread serverThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// create the server socket
ServerSocket server = new ServerSocket(
8888, 5, InetAddress.getLocalHost());
// wait until clients try to connect
Socket client = server.accept();
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
// loop until the connection is closed
String line;
while ((line = in.readLine()) != null) {
// output what is received
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
Thread clientThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// connect with the server
Socket s = new Socket(InetAddress.getLocalHost(), 8888);
// attach to socket's output stream with auto flush turned on
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
// send some text
out.println("Start");
out.println("End");
// close the stream
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// start server
serverThread.start();
// wait a bit
Thread.sleep(1000);
// start client
clientThread.start();}添加回答
举报
0/150
提交
取消
