java socket初步学习一 ( tcp)

时间:2021-08-09 13:28:20

Java socket通信程序:

第一版本:

实现功能:

服务器地址:127.0.0.1  端口:5050

客户机:端口5050

客户端发送字符;“t”

服务器接收到该字符并回复:“r”

流程:

建立java工程,默认在workspace中,udpServer为工程名,此时work/udpServer文件夹

建立类名为server,则此时服务器代码为:

package udpServer;

import java.io.*;
import java.net.*; public class server { public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
ServerSocket listen = new ServerSocket(5050); Socket server = listen.accept(); InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream(); char c = (char)in.read();
System.out.println("收到:" + c); out.write('r'); out.close();
in.close();
server.close();
listen.close();
} }

建立java工程,由于eciplse不兼容同一个工作空间,此时修改临时工作空间路径为/workspace/udp

工程名为udpClient,那么对应物理路径为work/udp/udpClinet

类名为client,此时客户端代码:

package udpClient;

import java.io.*;
import java.net.*; public class client { public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub Socket client = new Socket("127.0.0.1" , 5050); InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream(); out.write('t'); char c = (char)in.read();
System.out.println("收到:" + c); out.close();
in.close();
client.close();
} }