收发数据使用byte类型
getBytes();将mesg转换成byte类型
服务端和客户端收发数据都必须使用对应的输入输出流
一、服务端
1.1 单一连接
package com.demo;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test {
public static void main(String[] args) {
int len = 0;
byte[] data = new byte[120];
ServerSocket socket;
try {
socket = new ServerSocket(7777);
System.out.println("socket服务端创建成功,等待连接");
Socket con = socket.accept();
System.out.println("客户端接入");
InputStream fd = con.getInputStream();
len = fd.read(data);
System.out.println("收到数据:"+new String(data, 0, len));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1.2 多个连接
package com.demo;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test {
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(7778);
System.out.println("socket服务端创建成功,等待连接");
while(true) {
final Socket con = socket.accept();
System.out.println("客户端接入");
Thread t = new Thread(new Runnable() {
public void run() {
InputStream fd = null;
try {
fd = con.getInputStream();
byte[] data = new byte[120];
int len = 0;
while(true){
len = fd.read(data);
System.out.println("收到数据:"+new String(data, 0, len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、客户端
package com.demo;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
try {
Socket client = new Socket("192.168.43.135", 8080);
OutputStream out = client.getOutputStream();
Scanner sc = new Scanner(System.in);
String data = sc.next();
out.write(data.getBytes());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}