JAVA问题:用socket编写一个服务器端程序 20
1个回答
展开全部
服务端:<pre t="code" l="java"> ServerSocket serverSocket = new ServerSocket(2008);
while (true) {
Socket socket = serverSocket.accept();
MyThread thread = new MyThread(socket);
thread.start();
}<pre t="code" l="java">public class MyThread extends Thread {
private Socket socket;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
super.run();
try {
InputStream is = socket.getInputStream();
BufferedReader bufReader = new BufferedReader(new InputStreamReader(is));
String line = "";
String s = "";
while ((s = bufReader.readLine()) != null) {
line = line + s;
}
System.out.println("接收到:" + line);
} catch (IOException e) {
e.printStackTrace();
}
}
}客户端:
<pre t="code" l="java">public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket=new Socket("192.168.0.101", 2008);
OutputStream out=socket.getOutputStream();
PrintWriter pw=new PrintWriter(new OutputStreamWriter(out));
pw.print("12345上山打老虎");
pw.flush();
pw.close();
out.close();
}
while (true) {
Socket socket = serverSocket.accept();
MyThread thread = new MyThread(socket);
thread.start();
}<pre t="code" l="java">public class MyThread extends Thread {
private Socket socket;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
super.run();
try {
InputStream is = socket.getInputStream();
BufferedReader bufReader = new BufferedReader(new InputStreamReader(is));
String line = "";
String s = "";
while ((s = bufReader.readLine()) != null) {
line = line + s;
}
System.out.println("接收到:" + line);
} catch (IOException e) {
e.printStackTrace();
}
}
}客户端:
<pre t="code" l="java">public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket=new Socket("192.168.0.101", 2008);
OutputStream out=socket.getOutputStream();
PrintWriter pw=new PrintWriter(new OutputStreamWriter(out));
pw.print("12345上山打老虎");
pw.flush();
pw.close();
out.close();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询