如何创建基本的Java Server? [英] How to create a basic Java Server?
问题描述
基本上,我需要一个可以连接多个人的基本Java Server,并且当一个连接的客户端(已经在Obj-c中进行了编码)向其发送数据时,它会将其发送回所有连接的人.
Essentially I want a basic Java Server which multiple people can be connected to and when one of the connected clients (Already coded in Obj-c) sends data to it, it sends it back to everyone who is connected.
我是一名真正的Java新手,在可预见的将来,我不会再需要Java了,但是我想尽快解决它,而不是从头开始学习Java.因此,如果有人对此有一些源代码或教程,那么将不胜感激.
I'm a real Java Newbie and I'm not going to need Java in the forseeable future for anything but this so I want it out the way as soon as possible rather than learning Java properly from scratch. So if anyone has some source code for this or perhaps a tutorial it would be greatly appreciated.
谢谢:) 奥兹(Ozzie)
Thanks :) Ozzie
推荐答案
这是Sun提供的一个简单的敲敲"服务器:
Here is a simple "Knock Knock" server courtesy of Sun:
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
没有比这更简单的东西了.
You can't get much simpler than this.
这篇关于如何创建基本的Java Server?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!