------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
只强调一点:
(1) Datagram Sockets:数据包socket,一般传输方式为UDP
(2) Stream Sockets:流socket,一般传输方式为TCP
Java通过两个类DatagramSocket和DatagramPacket来支持但Datagram socket(UDP)。Datagram Socket不真正区分Server和Client,既可以用来写server,也可以写client。但对于java中的Socket类和ServerSocket类就只能分别来写客户端和服务器端(同时支持TCP与UDP,更Socket(String
Socket与TCP、UDP
1、TCP实现
package myjava.net.socket.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketTCP extends Thread {
private Socket s;
public SocketTCP(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
os.write("Hello,welcome you!".getBytes());
byte[] buf = new byte[100];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
os.close();
is.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length > 0)
server();
else
client();
}
public static void server() {
try {
ServerSocket ss = new ServerSocket(6000);
while (true) {
Socket s = ss.accept();
new SocketTCP(s).start();
}
// ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void client() {
try {
Socket s = new Socket(InetAddress.getLocalHost(), 6000);
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
byte[] buf = new byte[100];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
os.write("Hello,this is zhangsan!".getBytes());
os.close();
is.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
多个客户同时连接:
主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。运用Thread类或Runnable接口来实现是不错的办法。
现在实现服务器端编程:(基于TCP方式)
MyServer .java
---------------------------------------------------
package server;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
//这个简单的socket服务器端主要是说句Hello XXX,采用多线程实现
public class MyServer extends Thread {
private Socket s;
public static void main(String[] args) {
}
public MyServer(Socket s) {
}
public void run() {
}
public static void server() {
}
}
客户端编程:
MyClient .java
---------------------------------
package client;
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
}
public static void client(String userName) {
}
}