java使用多线程编程,实现socket服务器客户端交互

时间:2022-12-21 22:15:00

自己写用来练习的小例子,大神请绕道

package cs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* 使用多线程编程,实现客户端发送长和宽,服务器接收参数并传回面积
*/
public class Test
{
public static void main(String[] args)
{
Thread server = new Thread(new Server());
server.start();
Thread client = new Thread(new Client());
client.start();
}
}

class Server implements Runnable
{

@Override
public void run()
{
ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter writer = null;
BufferedReader reader = null;
try
{
serverSocket = new ServerSocket(2000);
socket = serverSocket.accept();

reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String str = reader.readLine();
String result = handle(str);
writer = new PrintWriter(socket.getOutputStream());
writer.println(result);
writer.flush();
}
catch (IOException e)
{
System.out.println(e);
}
}

private String handle(String str)
{
String param[] = str.split(",");
int x = Integer.valueOf(param[0]);
int y = Integer.valueOf(param[1]);
System.out.println("Server : revice param:" + str);
return x * y + "";
}
}

class Client implements Runnable
{

@Override
public void run()
{
Socket socket = null;
PrintWriter writer = null;
BufferedReader reader = null;
try
{
socket = new Socket("127.0.0.1", 2000);
writer = new PrintWriter(socket.getOutputStream());

reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入长:");
String x = reader.readLine();
System.out.println("请输入宽:");
String y = reader.readLine();
String param = x + "," + y;
writer.println(param);
writer.flush();
reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
System.out.println("Client : result from server:"
+ reader.readLine());
}
catch (IOException e)
{
System.out.println(e);
}
}
}