客户端
package Liu.talk;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* 客户端
*
* @author liu
*/
public class TcpClient {
public static void main(String[] args) {
//1需要一个IP和端口
InetAddress serverIP = null;
Socket socket = null;
OutputStream os = null;
try {
serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//2创建一个socket连接
socket = new Socket(serverIP, port);
//3发送消息
os = socket.getOutputStream();
os.write("啊所发生的富商大贾水电费水电费水电费是电费".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务器
package Liu.talk;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器
*
* @author liu
*/
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1我得有一个IP和端口
serverSocket = new ServerSocket(9999);
//2等待客户端连接过来
accept = serverSocket.accept();
//3读取客户端的消息
is = accept.getInputStream();
/* //输入文字,会乱码
int count = 0;
byte[] A=new byte[1];
while ((count = is.read(A)) != -1) {
System.out.println(new String(A,0,count));
}*/
//管道流
baos = new ByteArrayOutputStream();
int count = 0;
byte[] A = new byte[1];
while ((count = is.read(A)) != -1) {
baos.write(A, 0, count);
}
System.out.println(baos.toString());
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}