gpt4 book ai didi

Android服务器和客户端连接

转载 作者:行者123 更新时间:2023-11-30 02:34:24 24 4
gpt4 key购买 nike

我一直在尝试开发一个 android 应用程序,它可以向其他设备(如带有 wi-fi 模块的指示器)发送命令,如“S”、“A”或“B”。因此,我正在尝试使用 wi-fi 在我的 android 设备和 wi-fi 模块之间建立这种连接。

我在 android 开发者网站上搜索了一些信息。我不知道为什么在服务器边缘,我只需要提供“端口”的信息。而在客户端端,我必须提供“端口”和“地址”的信息。

最佳答案

您好,我可以提供一些代码来简单连接到在 java 中运行的服务器,仅使用控制台和使用套接字连接连接到服务器的基本 android 应用程序。它只是在模拟器(例如来自 Eclipse 的模拟器)上运行的示例代码。真的希望它有所帮助。将通过一些步骤很快提供一个更好的例子。只要手机使用的是 android,当然还有 sdk 版本 14 及更高版本。代码不是很干净,稍后我也会这样做。

Android 端使用 AsyncTask 的 MainActivity.java

    public class MainActivity extends Activity {

Socket socket = null;
DataOutputStream output;
DataInputStream input;
ObjectInputStream objectInput;
Button buttonConnect;
Button createTest;
TextView textResponse;

EditText subjectInput, gradeInput, testNameInput;
String curSubject, curGrade, curName;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonConnect = (Button) findViewById(R.id.buttonConnect);
createTest = (Button) findViewById(R.id.createTest);
textResponse = (TextView) findViewById(R.id.textResponse);

buttonConnect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new ConnectThread().execute("Connect");
buttonConnect.setText("Connected");
}
});
createTest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
subjectInput = (EditText) findViewById(R.id.editText1);
gradeInput = (EditText) findViewById(R.id.editText2);
testNameInput = (EditText) findViewById(R.id.editText3);
ConnectThread thread = new ConnectThread(subjectInput.getText()
.toString(), gradeInput.getText().toString(),
testNameInput.getText().toString());
thread.execute("createOpen");
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

public class ConnectThread extends AsyncTask<String, String, String> {
String response = "Nothing yet";
String subject, grade, name;

public ConnectThread() {
}

public ConnectThread(String subject, String grade, String name) {
this.subject = subject;
this.grade = grade;
this.name = name;
}

@Override
protected String doInBackground(String... params) {
if (params[0].equals("Connect")) {
connect();
}
if (params[0].equals("createOpen")) {
createOpen();
}
return null;
}

@Override
protected void onPostExecute(String result) {
textResponse.setText(response);
super.onPostExecute(result);
}

public void createOpen() {
try {
output.writeUTF("createOpen");
output.writeUTF(subject);
output.writeUTF(grade);
output.writeUTF(name);
String command = input.readUTF();
if (command.equals("null")) {
try {
Object object = objectInput.readObject();
ArrayList<String> curTest = (ArrayList<String>) object;
curName = curTest.get(0);
curGrade = curTest.get(1);
curSubject = curTest.get(2);
response = "New Test Created: " + curName;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
if (command.equals("exists")) {
try {
Object object = objectInput.readObject();
ArrayList<String> curTest = (ArrayList<String>) object;
curName = curTest.get(0);
curGrade = curTest.get(1);
curSubject = curTest.get(2);
response = "Test already exists: " + curName;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

public void connect() {
try {
socket = new Socket("10.0.0.16", 500);
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
objectInput = new ObjectInputStream(socket.getInputStream());
String command = input.readUTF();
response = command;
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("fail", e.toString());
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("fail", e.toString());
response = "IOException: " + e.toString();
}
}

public void disconnect() {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Java 的服务器类,它为客户端线程创建套接字

public class Server {
DataOutputStream os;
DataInputStream is;
ArrayList<Test> tests;

public static void main(String[] args) {
new Server();
}

public void postSystemMessage(String message) {
System.out.println(message);
}

public Server() {
try {
tests = new ArrayList<Test>();
// initial data set up
System.out.println("Starting server");
ServerSocket server = new ServerSocket(500, 100);
System.out.println("Server started");
System.out.println("----------------------------------");
while (true) {
System.out.println("Waiting for connection");
Socket socket = server.accept();
ServerThread connection = new ServerThread(socket, this);
System.out.println("New client connected");
System.out.println("----------------------------------");
connection.start();
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName())
.log(Level.SEVERE, null, ex);
}
}

public synchronized Test checkifexists(String subject, String grade,
String name) {
for (Test test : tests) {
if (test.getTestName().equals(name)) {
if (test.getGrade().equals(grade)) {
if (test.getSubject().equals(subject)) {
return test;
}
}
}
}
return null;
}

public synchronized Test createTest(String subject, String grade,
String name) {
Test test = new Test(subject, grade, name);
tests.add(test);
return test;
}

public synchronized void addToTests(Test in) {
tests.add(in);
}
}

为多客户端连接设置的服务器线程类

public class ServerThread extends Thread {
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
private ObjectOutputStream objectOutput;
private Server server;

public ServerThread(Socket socket, Server server) {
this.server = server;
this.socket = socket;
}

@Override
public void run() {
try {
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
objectOutput = new ObjectOutputStream(socket.getOutputStream());
out.writeUTF("connection successful");
String command = "";
while (!command.equals("quit")) {
command = in.readUTF();
if (command.equals("createOpen")) {
createOpen();
} else if (command.equals("getFile")) {
} else if (command.equals("saveFile")) {
} else if (command.equals("quit")) {
System.out.println("A client has left");
}
}
} catch (IOException e2) {
System.out.println("Connection dropped");
e2.printStackTrace();
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

public void createOpen() {
try {
String subject = in.readUTF();
String grade = in.readUTF();
String name = in.readUTF();
Test curTest = server.checkifexists(subject, grade, name);
if (curTest == null) {
Test test = server.createTest(subject, grade, name);
server.addToTests(test);
ArrayList<String> toSendTest = new ArrayList<String>();
toSendTest.add(subject);
toSendTest.add(grade);
toSendTest.add(name);
out.writeUTF("null");
System.out.println("sending object");
objectOutput.writeObject(toSendTest);
objectOutput.flush();
System.out.println("object sent");
} else {
ArrayList<String> toSendTest = new ArrayList<String>();
toSendTest.add(subject);
toSendTest.add(grade);
toSendTest.add(name);
out.writeUTF("exists");
System.out.println("sending object");
objectOutput.writeObject(toSendTest);
objectOutput.flush();
System.out.println("object sent");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}

关于Android服务器和客户端连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26830591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com