服务器端(Server)非多线程
package com.zeph.serverclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5678);
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if (str.equals("end"))
break;
}
client.close();
}
}
客户端(Client)
package com.zeph.serverclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class MyClient {
static Socket server;
public static void main(String[] args) throws Exception {
server = new Socket(InetAddress.getLocalHost(), 5678);
BufferedReader in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = wt.readLine();
out.println(str);
out.flush();
if (str.equals("end")) {
break;
}
System.out.println(in.readLine());
}
server.close();
}
}
服务器端(Server)多线程
package com.zeph.multiclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiClient extends Thread {
private Socket client;
public MultiClient(Socket c) {
this.client = c;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
// Mutil User but can't parallel
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if (str.equals("end"))
break;
}
client.close();
} catch (IOException ex) {
} finally {
}
}
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5678);
while (true) {
// transfer location change Single User or Multi User
MultiClient mc = new MultiClient(server.accept());
mc.start();
}
}
}
测试这个代码的时候可以直接用DOS控制台上面运行,这样看的效果更清楚!
服务器基本步骤:
1.指定端口实例化一个SeverSocket
2.调用ServerSocket的accept()方法,以在等待连接期间造成阻塞
3.获取位于该底层的Socket的流以进行读写操作
4.将数据封装成流
5.对Socket进行读写
6.关闭打开的流
客户端基本步骤:
1.通过IP地址和端口实例化Socket,请求连接服务器
2.获得Socket上的流以进行读写
3.把流封装进BufferedReader/PrintWriter的实例
4.对Socket进行读写
5.关闭打开的流
Java Socket编程教程:http://www.6acf.com/tutorial_java_advance/683.html
以上就是极悦java培训机构的小编针对“Java socket编程多线程,标准范例”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习