用java socket实现client与server通信,客户端向服务端发送字符串, 服务端再返回,把返回的变成大写。 20
1个回答
2017-08-17
展开全部
- import java.io.InputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- *
- * @TODO:Socket服务端
- */
- public class SocketServer {
- public static void main(String[] args) {
- // TCP通信
- ServerSocket serverSocket = null;
- try {
- serverSocket = new ServerSocket(3000);
- Socket socket = serverSocket.accept();
- InputStream inputStream = socket.getInputStream();
- byte[] byt = new byte[1024];
- int length = 0;
- // 开始读取
- while ((length = inputStream.read(byt)) != -1) {
- System.out.println(new String(byt, 0, length)); //这修改一下
- }
- } catch (Exception e) {
- }
- }
- }
client
- import java.io.ByteArrayInputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.util.Scanner;
- public class Test {
- public static void main(String[] args) {
- Socket socket = null;
- InputStream inputStream = null;
- Scanner scanner = new Scanner(System.in);
- String content = "";
- try {
- socket = new Socket("192.168.1.12", 3000);
- while (!(content = scanner.nextLine()).equals("exit")) {
- OutputStream outputStream = socket.getOutputStream();
- inputStream = new ByteArrayInputStream(content.getBytes());
- byte[] byt = new byte[1024];
- int length = 0;
- // 开始读取
- while ((length = inputStream.read(byt)) != -1) {
- outputStream.write(byt, 0, length);
- }
- }
- scanner.close();
- inputStream.close();
- } catch (Exception e) {
- }
- }
- }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询