1.socket javaԴ?源码?
2.编写一个简单的TCP通信程序。服务器发送“你好我是源码服务器”,客户端接收该信息并显示在屏幕上。源码闪送的源码用Java写
socket javaԴ?源码?
//客户端
public static void main(String[] args) throws Exception
{
Socket socket = new Socket(".0.0.1", );
OutputStream os = socket.getOutputStream();
os.write("hello world".getBytes());
os.close();//客户端使用完流之后记得要关闭!!源码源码装包
}
//服务端
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket();
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
byte[] buffer = new byte[];
int length = 0;
while (-1 != (length = is.read(buffer,源码空气指标源码 0, buffer.length)))//这句错了,是源码不等于!
{
String str = new String(buffer,源码 0, length);
System.out.println("welcome "+str);
}
}
编写一个简单的TCP通信程序。服务器发送“你好我是源码服务器”,客户端接收该信息并显示在屏幕上。源码用Java写
1、源码服务器端import java.io.DataOutputStream;import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private static final int PORT = ;
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(PORT);
while (true) {
Socket client = server.accept();
new Thread(new Server(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server implements Runnable {
private Socket client;
public Server(Socket client) {
this.client = client;
}
public void run() {
DataOutputStream output = null;
try {
output = new DataOutputStream(client.getOutputStream());
output.writeUTF("你好我是源码服务器");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) output.close();
output = null;
} catch (IOException e) { }
}
}
}
2、客户端
import java.io.DataInputStream;import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends Socket {
private static final int PORT = ;
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket(".0.0.1",源码wifi 源码 github PORT);
DataInputStream in = new DataInputStream(socket.getInputStream());
String res = in.readUTF();
System.out.println(res);
if (in != null) in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) { }
}
}
}
}