首页 > 代码库 > Java Socket通信 客户端服务器端基本代码

Java Socket通信 客户端服务器端基本代码

【服务器端】

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer {

	public static void main(String[] args) {
		try {
			System.out.println("启动服务端");
			ServerSocket sv = new ServerSocket(2233);
			//等待用户链接
			Socket socket = sv.accept();
			System.out.println("有用户链接!");
			while (true) {
				//1
				InputStream is = socket.getInputStream();
				//2
				byte[] data = http://www.mamicode.com/new byte[128];>

【客户机端】

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TestClient {

	public static void main(String[] args) {
		try {
			Socket socket = new Socket("192.169.191.4", 2244);
//			Socket socket = new Socket("localhost", 2233);
			System.out.println("链接服务器成功!");
			while (true) {
				System.out.println("请输入内容:");
				//1
				Scanner input = new Scanner(System.in);
				String msg = input.next();
				//2
				OutputStream os = socket.getOutputStream();
				//3
				byte[] data = http://www.mamicode.com/msg.getBytes("UTF-8");>

Java Socket通信 客户端服务器端基本代码